访问请求。获取或请求。在Django形式

时间:2021-05-23 11:44:32

In django view, we often call forms and initialize it with request.GET and/or request.POST values MyForm(request.GET) or MyForm(request.POST). How can I access it in form class?

在django视图中,我们经常调用表单并请求进行初始化。获得和/或请求。POST值MyForm(request.GET)或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 个解决方案

#1


2  

In your views.py:

在你views.py:

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

In your forms.py:

在你forms.py:

class MyForm(forms.ModelForm):
    ...

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

** Update **

* * * *更新

Originally misunderstood the intent of the author. To access just the data given by the request.GET or request.POST arguments, you can access them via self.data after calling super on the __init__ method.

最初误解了作者的意图。只访问请求提供的数据。获取或请求。发布参数,您可以通过self访问它们。在__init__方法上调用super之后的数据。

#1


2  

In your views.py:

在你views.py:

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

In your forms.py:

在你forms.py:

class MyForm(forms.ModelForm):
    ...

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

** Update **

* * * *更新

Originally misunderstood the intent of the author. To access just the data given by the request.GET or request.POST arguments, you can access them via self.data after calling super on the __init__ method.

最初误解了作者的意图。只访问请求提供的数据。获取或请求。发布参数,您可以通过self访问它们。在__init__方法上调用super之后的数据。