尝试创建如下评论表单:
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)
如果我提交表单,它会返回:“用户”对象没有“获取”属性。我确定我做错了什么,但我不知道是什么。