我试图在我的django应用程序中添加评论功能,但是无论我做什么,提交的评论都不会显示在数据库中,无法弄清原因。这是我使用过的一些代码,请看看。
models.py部分
class Comment(models.Model):
name = models.CharField(max_length=80)
email = models.EmailField()
text = models.TextField()
post = models.ForeignKey(Post, related_name='comments')
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
active = models.BooleanField(default=True)
class Meta:
ordering = ('created',)
verbose_name="评论"
verbose_name_plural="评论"
def __str__(self):
return 'Comment by {} on {}'.format(self.name, self.post)
forms.py部分
from django import forms
from .models import Comment
class CommentForm(forms.ModelForm):
class Meta:
model=Comment
fields=('name','email','text')
views.py部分
def post_comment(request,id):
post=get_object_or_404(Post,id=id)
if request.method=='POST':
form=CommentForm(request.POST)
if form.is_valid():
name=request.POST.get('name','')
email=request.POST.get('email','')
text=request.POST.get('text','')
comment=Comment(name=name,email=email,text=text,post=14)
comment.save()
return redirect(post)
else:
form=CommentForm()
comment_list = post.comments.all()
context={
'post':post,
'form':form,
'comment_list':comment_list
}
return render(request,'post_detail.html',context=context)
return redirect(post)
和post_detail.html部分
<form action="" method="POST" class="mb-5">{% csrf_token %}
<div class="form-group">
<label for="exampleInputPassword1">名称</label>
<input name="name" type="name" class="form-control" id="exampleInputPassword1" placeholder="Name">
</div>
<div class="form-group">
<label for="exampleInputEmail1">邮箱</label>
<input name="email" type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter email">
<small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
</div>
<div class="form-group">
<label for="exampleFormControlTextarea1">评论</label>
<textarea name="text" class="form-control" id="exampleFormControlTextarea1" placeholder="Comment area..." rows="5"></textarea>
</div>
<button type="submit" class="btn btn-primary" value="post_comment">提交</button>
</form>
有什么建议吗?谢谢。
答案 0 :(得分:0)
您在这里做错了两件事。第一个是您要手动呈现表单,并且HTML中没有任何内容可以显示表单错误。您需要按照documentation中所述将错误添加到HTML中,或者直到您使用{{ form.as_p }}
即使在那之后,它仍然无法工作,因为视图中的python代码是错误的。
if form.is_valid():
name=request.POST.get('name','')
email=request.POST.get('email','')
text=request.POST.get('text','')
comment=Comment(name=name,email=email,text=text,post=14)
comment.save()
return redirect(post)
else:
form=CommentForm()
上面的最后两行代码会导致在表单无效时创建新表单。这将丢弃任何过帐的表单数据。这也意味着您遇到的任何错误都将被丢弃。正确的代码如下所示:
post=get_object_or_404(Post,id=id)
if request.method=='POST':
form=CommentForm(request.POST)
if form.is_valid():
# don't directly use the request post data. Always use form.cleaned_data
name= form.cleaned_data['name'
.....
comment=Comment(name=name,email=email,text=text,post=14)
comment.save()
# the following redirect is wrong. Here post is an object
# you retrieved from a database, we usually redirect to a URL
return redirect(post)
else:
form = CommentForm()
comment_list = post.comments.all()
context={
'post':post,
'form':form,
'comment_list':comment_list
}
return render(request,'post_detail.html',context=context)
答案 1 :(得分:0)
尝试创建注释类:
class Comment(models.Model):
post = models.ForeignKey('blog.Post', on_delete=models.CASCADE, related_name='comments')
author = models.CharField(max_length=200)
text = models.TextField()
created_date = models.DateTimeField(default=timezone.now)
approved_comment = models.BooleanField(default=False)
def approve(self):
self.approved_comment = True
self.save()
def __str__(self):
return self.text
在管理面板中注册评论模型
要在管理面板中注册评论模型,请转至blog / admin.py并添加以下行:
admin.site.register(Comment)
直接在此行下:
admin.site.register(Post)
还记得将注释模型导入文件顶部,如下所示:
from django.contrib import admin
from .models import Post, Comment
admin.site.register(Post)
admin.site.register(Comment)
使我们的评论可见HTML:
<hr>
{% for comment in post.comments.all %}
<div class="comment">
<div class="date">{{ comment.created_date }}</div>
<strong>{{ comment.author }}</strong>
<p>{{ comment.text|linebreaks }}</p>
</div>
{% empty %}
<p>No comments here yet :(</p>
{% endfor %}