如何在表单类中访问会话变量

时间:2018-09-11 11:49:26

标签: django django-forms

嗨,我有一个会话变量城市,如何在表单类中访问它。

类似这样的东西

LonginForm(forms.Form)类:

current_city=request.city

1 个答案:

答案 0 :(得分:1)

默认情况下,Form无权访问request对象,但是您可以使构造器将其考虑在内并进行处理。例如:

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

然后在相关视图中,您需要传递请求对象,例如:

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

或在基于基于类的视图中:

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