Django:使用 from 创建对象时出错

Django: Error when creating objects using from

我一直在尝试使用表单来插入评论。当用户输入评论时,它会获取文章编号、用户名和评论正文,并重定向到上一页。但是它一直显示错误消息,我找不到我错过的确切部分。

这是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'),

这个问题中有很多非常非常奇怪的代码。一些建议:

  • 在会话中设置 username 没有意义,因为用户已经通过请求可用。
  • if 'username' is None 将文字字符串 "username" 与 None 进行比较,这永远不会为真。
  • 如果用户未登录,您应该重定向到主页,而不是呈现主页模板。
  • 不要使用has_key;确定字典是否有键的正确方法是 if key in dict.
  • 不要和== False比较。表达式 (inhas_key) 的结果已经是一个布尔值,即真或假。
  • 您完全忽略了表格,因为您直接将所有值与 request.POST 进行了比较。你应该在调用 form.is_valid().
  • 之后使用 form.cleaned_data 字典
  • 但是无论如何你都不需要比较那些东西,因为它们正是表单验证所捕获的东西;这就是重点。
  • 您不能将关键字参数传递给表单。你传数据字典,即request.POST。然后调用 is_validsave.
  • 实例化表单的结果 class 是表单实例,而不是模型实例。模型实例来自调用 form.save().
  • instance.Comment += 1 字面上根本没有意义;表单和模型都没有 Comment 属性。
  • 永远不会做一个空白try/except。那只是隐藏了错误。完全删除这些语句。