将自定义参数添加到django modelform

时间:2017-04-03 14:40:52

标签: django django-forms

我在向模型表单添加自定义参数时遇到了麻烦(在这种情况下,来自request.user的currrent用户) 我曾经在以前的项目中这样做,我无法设法使它在Django 1.10.4上的新项目上工作。

我收到了这个错误:

apartment = get_object_or_404(Apartment, pk=apartment_id)
if request.method == 'POST':
    form = ApartmentForm(request.POST, request.FILES, instance=apartment, user=request.user)
    if form.is_valid():
        form.save()
        return redirect('list_realestateprogram_apartment', realestateprogram_id=apartment.realestateprogram.id)
    else:
        print form.errors
else:
    form = ApartmentForm(instance=apartment, user=request.user)

这是我的观点:

class ApartmentForm(forms.ModelForm):
    class Meta:
        model = Apartment
        exclude = ('realestateprogram',)

    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user')
        super(ApartmentForm, self).__init__(*args, **kwargs)

这是我的表格:

{{1}}

如果你能帮助我,请提前致谢

1 个答案:

答案 0 :(得分:0)

尝试使用关键字参数传递所有值:

form = ApartmentForm(data=request.POST, files=request.FILES, instance=apartment, user=request.user)

如果您查看class based generic views,那就是他们如何做到的。我还建议您查看Form handling with class-based views