Python Django:使用从创建对象时出错
我一直在尝试使用表单插入评论。当用户输入comment时,它将获得文章编号、用户名和注释正文,并重定向到上一页。然而,它一直显示错误消息,我无法准确地找到我遗漏的部分 这是model.pyPython Django:使用从创建对象时出错,python,django,web,django-forms,views,Python,Django,Web,Django Forms,Views,我一直在尝试使用表单插入评论。当用户输入comment时,它将获得文章编号、用户名和注释正文,并重定向到上一页。然而,它一直显示错误消息,我无法准确地找到我遗漏的部分 这是model.py class Comment(models.Model): article_no = models.IntegerField(default=1) comment_no = models.AutoField(primary_key=True) comment_writer = models.CharField(
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')
url.py
url(r'^comment/(?P<article_no>[0-9]+)/$', views.comment, name='comment'),
url(r'^comment/(?P[0-9]+)/$”,views.comment,name='comment'),
这个问题中有很多非常奇怪的代码。一些建议:
- 在会话中设置
没有意义,因为用户已经可以通过请求访问username
将文字字符串“username”与None进行比较,这永远不会是真的如果'username'为None
- 如果用户未登录,则应重定向到主页,而不是呈现主页模板
- 不要使用
;确定dict是否有键的正确方法是has_键
if key in dict
- 不要将事物与
进行比较。表达式(中的==False
或
)的结果已经是一个布尔值,该值为true或false具有_key
- 您完全忽略该表单,因为您直接将所有值与
进行比较。调用request.POST
后,您应该使用form.is\u valid()
dictform.cleaned\u data
- 但无论如何,您不需要比较这些东西,因为它们正是表单验证所捕获的东西;这就是重点
- 不能将关键字参数传递给窗体。您传递数据字典,即
。然后调用request.POST
和是有效的
保存
- 实例化表单类的结果是表单实例,而不是模型实例。模型实例来自调用
form.save()
字面上毫无意义;表单和模型都没有Comment属性instance.Comment+=1
- 永远不要做空白的尝试。这只是隐藏了错误。完全删除这些语句
instance=CommentForm(comment\u body=comment\u body,comment\u writer=comment\u writer,article\u no=article\u no)instance.save()是错误的。您传递了一个dict(通常是请求。POST
)或initial=dict
。非常感谢您,我更改了代码,代码变得比以前更好了。