user2959896
user2959896

Reputation:

User session object is not available on POST in django?

I have a form where users are submitting data. One of the fields is "author" which i automatically fill in by using the {{ user }} variable in the template, it will have the username if the user is logged in and AnonymousUser if not. This {{ user }} is not part of the form, just text.

When a user submits the form i need to see which user, or if this was an anonymous user that submitted the data so i though i would use the request.session['user'] but this doesnt work since the user key is not available. I tried setting the request.session['user'] value to the user object but the session dictionary doesnt accept objects, it says its not JSON serializable.

I though the context processors would add this user variable to it was also available to the view but it isnt. I need a user object and not just the user name to save to the database along with the form. Is there any way to extract the user object when its not part of the form and the user is logged in ? I need to associate the submitted data with a user or an anonymous user and the foreign key requires an object which i also think is must convient to work with when extracting the data from the DB again.

I dont see it being helpful to post any code here since this is a question of how to extract a user object after a post and not specifically a problem with the code.

Upvotes: 0

Views: 142

Answers (2)

Gabriel Amram
Gabriel Amram

Reputation: 2790

Your view gets the request object so it has the "user" attribute, as such => request.user

if your problem is getting this user object while in the form you can override the save method of the form so it gets a user object and do whatever you need there with it.

def save(self, user):
     # do something with user

and when calling the method:

form.save(request.user)

Upvotes: 1

Daniel Roseman
Daniel Roseman

Reputation: 599946

The user is never in request.session. It's directly on the request object as request.user.

Upvotes: 0

Related Questions