0

尝试创建如下评论表单:

class CommentCreationForm(forms.Form):
    body = forms.CharField(widget=forms.Textarea)
    author = forms.CharField()

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

    def save(self):
        data = self.cleaned_data
        comment = Comment(body=data['body'], author=data['author'], user=self.user)
        comment.save()

    def clean(self):
        return self.cleaned_data

视图.py

@login_required
def create(request):
    try:
        if is_post(request):
            form = CommentCreationForm(request.user)
            if form.is_valid():
                print 'valid'
                form.save()
                return render_to_response("login.html", context_instance = RequestContext(request))
            return render_to_response("login.html", context_instance = RequestContext(request))
        return render_to_response("create.html", {'form':CommentCreationForm()}, context_instance = RequestContext(request))
    except Exception as e:
        print str(e)

如果我提交表单,它会返回:“用户”对象没有“获取”属性。我确定我做错了什么,但我不知道是什么。

4

1 回答 1

0

首先,表单初始化不正确,签名Form.__init__如下:

Form.__init__(data=None, files=None, ...)

# When you put
form = CommentCreationForm(request.user)
# The data is feed w/ request.user ...

其次,self.user = kwargs.pop('user', None)将始终设置self.userNone,除非调用代码是:

form = CommentCreationForm(request.POST, user=request.user) 

最后,更好的方法是在某些范围内直接引用request.user,例如:

def make_commment_form_cls(user):

    class CommentCreationForm(forms.Form):
        body = forms.CharField(widget=forms.Textarea)
        author = forms.CharField()

        def save(self):
            data = self.cleaned_data
            # HERE
            comment = Comment(body=data['body'], author=data['author'], user=user)
            comment.save()

    return CommentCreationForm

在创建视图中

# replace 
form = CommentCreationForm(request.user)
# with
form = make_comment_form_cls(request.user)(request.POST)
于 2013-03-09T12:15:17.427 回答