1

I'm writing my first django project and I'm trying to make it as basic as possible. Rather than authenticating users, for the time being, I'm using cookies to identify people (if my understanding of what I'm doing is correct). In my views.py, I have a method that does the following:

request.session["username"] = request.POST.get('username')

How do I set request.session["username"] within tests.py?

request.session["username"] = "Barry" doesn't seem to work, and neither does self.client.session["username"] = "Barry". I've been trying a few things that I saw at https://docs.djangoproject.com/en/1.9/topics/http/sessions/#using-sessions-out-of-views but there is a good chance that I haven't done it properly as I don't really understand what I'm doing. I also found this: Setting a session variable in django tests which gave me NameError: global name 'import_module' is not defined when I tried to use it. Any help or suggest reading (preferably beginner level) is appreciated.

jazzabeanie
  • 425
  • 4
  • 15

1 Answers1

3

The documentation tells you how to use the session in the client. In particular, note the need to assign the current session to a variable before modifying it:

session = self.client.session
session['username'] = 'Barry'
session.save()
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • And the reason to put session into a variable, is because every time you write `self.client.session`, you get [new object](https://github.com/django/django/blob/2.2/django/test/client.py#L452-L463). – x-yuri Apr 06 '19 at 10:07