我有一个Django generic create view
class TestCreateView(CreateView):
form_class = TestCreateForm
##forms.py
class TestCreateForm(forms.ModelForm):
class Meta:
model = Test
def __init__(self, user, *args, **kwargs):
super(TestCreateForm).__init__(*args, **kwargs)
self.fields['test_field'] = Testing.objects.filter(user=user)
在基于功能的视图中,我会这样做:
form = TestCreateForm(request.user)
现在基于泛型类的视图我是否必须覆盖get
和post
方法?
答案 0 :(得分:5)
class TestCreateView(CreateView):
form_class = TestCreateForm
def get_form_kwargs(self, **kwargs):
form_kwargs = super(TestCreateView, self).get_form_kwargs(**kwargs)
form_kwargs["user"] = self.request.user
return form_kwargs
答案 1 :(得分:0)
由于您需要在 init 中添加参数(每次实例化表单时),您可以执行的操作是覆盖CreateView类中的get_form_kwargs:
class TestCreateView(CreateView):
form_class = TestCreateForm
def get_form_kwargs(self):
kwargs = {
'initial': self.get_initial(),
'prefix': self.get_prefix(),
'user': self.request.user
}
if self.request.method in ('POST', 'PUT'):
kwargs.update({
'data': self.request.POST,
'files': self.request.FILES,
})
return kwargs