2

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
Maruthesh
  • 213
  • 3
  • 16

1 Answers1

4

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
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
  • I am working on the same but what how can I save it in the session? I am not able to access ```request.session['key']``` – Deshwal Sep 06 '19 at 19:29
  • @Deshwal: `self.request.session['key'] = ...`? That being said, session variables should be used scarcely, especially since these are not persistent. – Willem Van Onsem Sep 06 '19 at 19:31
  • Can You help me out if I put another Question after some time. Would You please see it. Because it is a bit complex to people and they don't see it. I'll post a link to my question here. Would you please answer it? – Deshwal Sep 06 '19 at 19:41
  • Can you please tell me why [this form ](https://stackoverflow.com/questions/57830992/error-while-accessing-request-sessionkey-inside-forms-using-checkboxselect) is not working as expected? – Deshwal Sep 07 '19 at 05:42