我正在尝试允许用户张贴答案和评论到一个特定的bloq问题Q&a
这是我的模型
class PostAnswer(models.Model):
""" Model for answering questions"""
question = models.ForeignKey(
PostQuestion,
on_delete=models.CASCADE,
related_name='comments',
)
text_content = models.TextField()
user = models.ForeignKey(
User,
on_delete=models.CASCADE,
)
approved_comment = models.BooleanField(default=False)
created_on = models.DateTimeField('published', auto_now_add=True)
class Meta:
ordering = ['created_on']
def approve(self):
self.approved_comment = True
self.save()
def __str__(self):
return 'comment by {} on {}'.format(self.user, self.question)
这是我在一个应用程序上的views.py
class Index(ListView):
queryset = PostQuestion.objects.all()
template_name = 'index.html'
context_object_name = 'posts'
paginate_by = 10
def detail(request, slug):
post = get_object_or_404(PostQuestion, slug=slug)
comments = post.comments.all()
new_comment = None
# comment posted
if request.method == 'POST':
form = CommentForm(data=request.POST)
if form.is_valid():
new_comment = form.save(commit=False)
new_comment.post = post
new_comment.save()
return HttpResponseRedirect(reverse('page:detail_view'))
else:
form = CommentForm()
context = {'post': post,
'comments': comments,
'new_comment': new_comment,
'form': form}
return render(request, 'detail.html', context)
我的应用程序表单:
class CommentForm(forms.ModelForm):
text_content = forms.CharField(widget=PagedownWidget())
class Meta:
model = PostAnswer
fields = ['text_content']
应用程序的urls.py视图
from .views import detail, ask, Index
from django.urls import path
urlpatterns = [
# path('<slug:slug>/comment', add_comment_to_post, name='add_comment_to_post'),
path('ask/', ask, name='ask'),
path('<slug:slug>', detail, name='detail_view'),
path('', Index.as_view(), name='index'),
]
下面是注释的html模板
<!--------Display a form for users to add a new comment------->
<h3>Leave a comment</h3>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="btn btn-primary btn-sm">Add Comment</button>
</form>
这是所有的代码,我认为您需要它来了解问题。 之前,寄存器部分我的代码,它工作正常,我不知道是否可以引起的问题为数据库或为什么不是所有的指令在视图。
该字段的名称是question
,而不是,因此您应该重写逻辑,以便:post
new_comment.question = post
但是,这仍然会引发错误,因为user
字段也没有填写。
然而,使用commit=false
并不是一个好主意,因为这样表单就不能再保存多对多字段了。 据我所见,目前还没有多对多字段,但尽管如此,如果以后添加这些字段,就必须重写逻辑。 您可以将视图改进为:
from django.contrib.auth.decorators import login_required
from django.shortcuts import redirect
@login_required
def detail(request, slug):
post = get_object_or_404(PostQuestion, slug=slug)
comments = post.comments.all()
if request.method == 'POST':
form = CommentForm(data=request.POST)
if form.is_valid():
form.instance.question = post
form.instance.user = request.user
form.save()
return redirect('page:detail_view', slug=slug)
else:
form = CommentForm()
context = {
'post': post,
'comments': comments,
'form': form
}
return render(request, 'detail.html', context)
注意:使用settings.auth_user_model
[Django-doc]引用用户模型通常比直接使用user
模型[Django-doc]更好。 有关更多信息,可以查看文档的“引用用户
模型”部分。
注意:您可以使用@login_required
decorator[Django-doc]将视图限制为经过身份验证的用户的视图。