【发布时间】:2017-02-15 08:18:04
【问题描述】:
我一直在尝试使用表单来插入评论。当用户输入评论时,它会获取文章编号、用户名和评论正文并重定向到上一页。但是它一直显示错误消息,我无法准确找到我错过的部分。
这是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'),
【问题讨论】:
-
它显示什么错误信息?
-
发布你得到了什么?
-
@EvansMurithi 它说'__init__() 得到了一个意外的关键字参数'comment_body''。所以我认为这可能是由于在字段名称上加上大写字母造成的,所以我把它改成了小写。但是结果是一样的。
-
似乎成功获取评论作者、评论正文、文章编号但未能在数据库中创建或插入行。
-
instance = CommentForm(Comment_body=comment_body, Comment_writer=comment_writer, Article_no=article_no) instance.save()是错误的。你传递一个字典(通常是request.POST)或initial=dict。
标签: python django web django-forms views