Skip to content
Advertisement

How to use Django session variable in models.py

I wanna use the Django session variable on models.py file. How can I do it?

I want to get the user’s Pincode/zip and have to run a query using that.

pin_code = #wanna get from session
price = ProductPrice.objects.get(product=self.pk, pincode=pin_code)

I need to get Pincode from the session.

Advertisement

Answer

In your model method you don’t have access to the request so you do not have access to the session. One way that you could call the method with the session is to add a template tag that passes the value from the session to your method

@register.simple_tag(takes_context=True)
def price(context, product):
    return product.get_price(pin_code=context.request.session.get('pin_code'))

In your template you would use the following, if the above code was added to a file with the path app_name/templatetags/product_tags.py

{% load product_tags %}

{% price item %}

Docs on where to put custom template tags

Advertisement