Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 981
Maruthesh Avatar asked Apr 26 '26 13:04

Maruthesh


1 Answers

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
like image 145
Willem Van Onsem Avatar answered Apr 29 '26 09:04

Willem Van Onsem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!