Django:CommentForm无法正常工作,没有错误?

时间:2013-03-09 09:02:13

标签: python django forms

尝试创建评论表格如下:

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

views.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)

如果我提交表单,则返回:'User'对象没有属性'get'。我确定我做错了什么,但我不知道是什么。

1 个答案:

答案 0 :(得分: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.user设置为None,除非调用代码为:

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)