问题描述
我正在创建一个博客网站,用户可以在其中在首页上发布文章,然后也可以使用表单对其发表评论。这些帖子还可以在网站上的其他位置,例如搜索结果和用户个人资料中查看。我想做的是允许用户在他们出现的任何地方对帖子发表评论。为此,我在评论表单中使用了一个包含标签,如下所示:
@register.inclusion_tag('posts/comment.html')
def comment_create_and_list_view(request):
profile = Profile.objects.get(user=request.user)
c_form = CommentModelForm()
if 'submit_c_form' in request.POST:
c_form = CommentModelForm(request.POST)
if c_form.is_valid():
instance = c_form.save(commit=False)
instance.user = profile
instance.post = Post.objects.get(id=request.POST.get('post_id'))
instance.save()
c_form = CommentModelForm()
context = {
'profile': profile,'c_form': c_form,}
return context
并且这样注册到我的网址中:
from django.urls import path
from .templatetags.custom_tags import comment_create_and_list_view
from .views import *
app_name = 'posts'
urlpatterns = [
path('comment/<int:pk>/',comment_create_and_list_view,name='comment'),]
我的表单如下:
class CommentModelForm(forms.ModelForm):
class Meta:
model = Comment
fields = ('body',)
comment.html看起来像这样:
<form action="{% url 'posts:comment' post.id %}" method="post">
{% csrf_token %}
<input type="hidden" name="post_id" value={{ post.id }}>
{{ c_form }}
<button type="submit" name="submit_c_form">Send</button>
</form>
我正在使用{% comment_create_and_list_view request %}
在尝试加载页面时,我在/错误处收到noreverseMatch:
Reverse for 'comment' with arguments '('',)' not found. 1 pattern(s) tried: ['comment/(?P<pk>[0-9]+)/$']
曾经在谷歌上搜索了几个小时,不知道我要去哪里错了...
解决方法
以防万一有一天对其他人有帮助,我通过重构包含标记以仅呈现表单来解决了问题:
@register.inclusion_tag('posts/comment.html')
def comment_tag():
c_form = CommentModelForm()
return {'c_form': c_form}
并添加了一个视图来处理提交:
def comment_view(request):
profile = Profile.objects.get(user=request.user)
if 'submit_c_form' in request.POST:
c_form = CommentModelForm(request.POST)
if c_form.is_valid():
instance = c_form.save(commit=False)
instance.user = profile
instance.post = Post.objects.get(id=request.POST.get('post_id'))
instance.save()
return redirect('posts:index')
然后我将comment.html调整为仅使用{{ c_form }}
来应用表单,并将模板标签和form元素包装在索引中:
<form action="{% url 'posts:comment' %}" method="post">
{% csrf_token %}
<input typ="hidden" name="post_id" value={{ post.id }}>
{% comment_tag %}
<button type="submit" name="submit_c_form">Send</button>
</form>