alias51
alias51

Reputation: 8608

How to store a primary key in a session variable

I am storing an object.pk in a session variable.

E.g. in template.html:

{{ request.session.myobject_pk }} <-- results in a numeric value e.g. 10
{{ myobject.pk }} <-- the same numeric value, 10

However, when I call these two values in an if statement, the primary key does not match the session variable:

{% if myobject.pk == request.session.myobject_pk %} <-- results in a False 

Why is this? Is the object an integer and the session variable a string? How can I fix this to use them both in a conditional logic statement like this?

EDIT

I set the session variable in a view:

class MyView(ProcessFormView):

    def post(self, request, *args, **kwargs):
        post_myobject_pk = request.POST.get('field_name')
        ...
        // do stuff
        ...
        request.session['myobject_pk'] = post_myobject_pk 

Upvotes: 0

Views: 249

Answers (1)

Iain Shelvington
Iain Shelvington

Reputation: 32244

Values in the POST dictionary will always be strings, you need to cast the value to an int

post_myobject_pk = int(request.POST.get('field_name'))

Upvotes: 2

Related Questions