在Django Forms中访问request.GET或request.POST

时间:2013-12-05 05:16:53

标签: django django-forms

在django视图中,我们经常调用表单并使用request.GET和/或request.POST值MyForm(request.GET) or MyForm(request.POST)对其进行初始化。如何在表单类中访问它?

class MyForm(forms.ModelForm):
  class Meta:
  #... more code

  def __init__(self, *args, **kwargs):
    super(MyForm, self).__init__(*args, **kwargs)
    #... how to access request.POST or request.GET here?

1 个答案:

答案 0 :(得分:2)

在views.py中:

def your_view(request):
    form = MyForm(request)  # or MyForm(request, request.POST, request.FILES)
    # your view code

在您的forms.py中:

class MyForm(forms.ModelForm):
    ...

    def __init__(self, request, *args, **kwargs):
        post = request.POST
        super(MyForm, self).__init__(*args, **kwargs)

**更新**

最初误解了作者的意图。要仅访问request.GET或request.POST参数提供的数据,您可以在self.data方法调用super之后通过__init__访问它们。