Maruthesh
Maruthesh

Reputation: 223

how to access session variable inside form class

Hi i have a session variable city, how to access it inside form class.

Something like this

class LonginForm(forms.Form):

current_city=request.city

Upvotes: 3

Views: 1873

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476594

A Form has by default no access to the request object, but you can make a constructor that takes it into account, and processes it. For example:

class LonginForm(forms.Form):

    def __init__(self, *args, request=None, **kwargs):
        super(LonginForm, self).__init__(*args, **kwargs)
        self.request = request  # perhaps you want to set the request in the Form
        if request is not None:
            current_city=request.city

In the related views, you then need to pass the request object, like:

def some_view(request):
    my_form = LonginForm(request=request)
    # ...
    # return Http Response

Or in a class-based view:

from django.views.generic.edit import FormView

class LonginView(FormView):
    template_name = 'template.html'
    form_class = LonginForm

    def get_form_kwargs(self, *args, **kwargs):
        kwargs = super(LonginView, self).get_form_kwargs(*args, **kwargs)
        kwargs['request'] = self.request
        return kwargs

Upvotes: 5

Related Questions