使用request.user的Django ModelForm继承导致__init__上的TypeError

时间:2014-07-30 08:25:54

标签: django inheritance modelform

尝试继承ModelForm以创建BaseForm来更新模型中的created_bymodified_by字段。 我的BaseForm就是

class BaseForm(ModelForm):

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

    def save(self, *args, **kwargs):
        kwargs['commit']=False
        obj = super(BaseForm, self).save(*args, **kwargs)
        if self.user:
            obj.modified_by = self.user.username            
        obj.save()
        return obj

儿童表格为

class InviteForm(BaseForm):

    class Meta:
        model = UserInvitation

我正在通过视图

以子格式传递请求
form = InviteForm(instance=instance,request=request)

然而它给出了错误

TypeError at /accounts/invitation/
__init__() got an unexpected keyword argument 'request'

如果我没有继承BaseForm并以子格式编写代码,即InviteForm,则错误不存在。

请告知我的错误,我不想重复每种形式的代码。

Traceback:
File "c:\Python27\lib\site-packages\django\core\handlers\base.py" in get_response
115.                         response = callback(request, *callback_args, **callback_kwargs)
File "c:\Python27\lib\site-packages\django\contrib\auth\decorators.py" in _wrapped_view
25.                 return view_func(request, *args, **kwargs)
File "C:\Python27\Lib\site-packages\django\bin\mysite\userplus\views.py" in invitation
87.         form = InviteForm(instance=instance,request=request)

Exception Type: TypeError at /accounts/invitation/
Exception Value: __init__() got an unexpected keyword argument 'request'

1 个答案:

答案 0 :(得分:-1)

要更新UserInvitation模型中的modified_by字段,您应该将其排除在表单中显示:

class BaseForm(ModelForm):

...

class InviteForm(BaseForm):

    class Meta:
        model = UserInvitation
        exclude = ('modified_by',)

然后在你看来

form = InviteForm(request.POST, instance=instance)
if form.is_valid():
    invite = form.save(commit=false)
    invite.modified_by = request.user
    invite.save()

这样就可以使用提出请求的用户。

或者,您可以事先设置用户:

# views.py
instance = Invite(modified_by=request.user)
form = InviteForm(request.POST, instance=instance)
...