在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?
答案 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__
访问它们。