Django在窗体上创建视图参数

时间:2014-05-10 12:15:12

标签: django django-generic-views

我有一个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)

现在基于泛型类的视图我是否必须覆盖getpost方法?

2 个答案:

答案 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