我一直在尝试使用表单插入评论。当用户输入评论时,它会获得文章编号,用户名和评论正文,并重定向到上一页。但是它会显示错误信息,而我无法准确找到错过的部分。
这是model.py
class Comment(models.Model):
article_no = models.IntegerField(default=1)
comment_no = models.AutoField(primary_key=True)
comment_writer = models.CharField(max_length=50)
comment_body = models.CharField(max_length=300)
comment_date = models.DateTimeField(editable=False, default=datetime.now())
forms.py
class CommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = ['article_no', 'comment_body', 'comment_writer']
view.py
@login_required
def comment(request, article_no):
user = request.user
request.session['username'] = user.username
if 'username' is None:
return render(request, 'blog/home.html')
else:
if request.POST.has_key('comment_body') == False:
return HttpResponse('comment is none')
else:
if len(request.POST['comment_body']) == 0:
return HttpResponse('comment is none')
else:
comment_body = request.POST['comment_body']
print(comment_body)
if request.POST.has_key('comment_writer') == False:
return HttpResponse('writer is none')
else:
if len(request.POST['comment_writer']) == 0:
return HttpResponse('comment is none')
else:
comment_writer = request.POST['comment_writer']
print(comment_writer)
try:
instance = CommentForm(Comment_body=comment_body, Comment_writer=comment_writer, Article_no=article_no)
instance.save()
instance.Comment += 1
instance.save()
#return HttpResponse('comment added')
item = get_object_or_404(Article, pk=article_no)
return render(request, 'blog/detail.html', {'item': item})
except:
print("A")
return HttpResponse('error')
print("B")
return HttpResponse('error')
urls.py
url(r'^comment/(?P<article_no>[0-9]+)/$', views.comment, name='comment'),
答案 0 :(得分:0)
在这个问题中有一个非常奇怪的代码的很多。一些指示:
username
没有意义,因为用户已经可以通过请求获得。if 'username' is None
比较文字字符串&#34;用户名&#34;没有,这永远不会是真的。has_key
;确定dict是否有密钥的正确方法是if key in dict
。== False
进行比较。表达式(in
或has_key
)的结果已经是布尔值,无论是真还是假。request.POST
进行比较。调用form.cleaned_data
后,您应该使用form.is_valid()
字典。request.POST
。然后拨打is_valid
和save
。form.save()
。instance.Comment += 1
根本没有任何意义;表单和模型都没有Comment属性。