我正在开发一个博客,我想在其中添加评论表格选项,我已将表格直接添加到文章的同一页面,我希望用户评论它应该重定向到同一页面的文章但我一直得到和错误 这是我的代码 查看
def comment(request, article_id):
try:
article = Article.objects.get(pk=article_id)
if request.method == 'POST':
form = CommentForm(request.POST)
if form.is_valid():
comment = form.cleaned_data['comment']
article.comments_set.create(comment=comment)
#messages.infos(request,comment)
return redirect('blog:_article')
#else:
#pass
#form = CommentForm()
#context['form'] = form
#return render(request,'blog/comment.html', context)
except Exception as e:
#wriet error to file
return render(request,'blog/404.html')
网址
from django.urls import path
from . import views
app_name = 'blog'
urlpatterns = [
path('', views.index, name='index'),
path('<int:article_id>/article', views._article, name='_article'),
path('<int:article_id>/comment', views.comment, name='comment'),
模型
class Comments(models.Model):
comment = models.TextField()
date = models.DateTimeField(default=timezone.now)
article = models.ForeignKey(Article, on_delete=models.CASCADE)
def __str__(self):
return self.comment
形式
<form method="post" action="{% url 'blog:comment' article.id %}">
{% csrf_token %}
{% for field in form %}
{{ field.label_tag }}
{% render_field field class="form-control is-valid" rows="4" %}
{% endfor %}<br>
<button class="btn btn-success">Post</button>
</form>
答案 0 :(得分:0)
如果您不希望页面重定向到其他页面或更新页面,则应使用AJAX(https://www.w3schools.com/jquery/jquery_ajax_get_post.asp)。您的表单会通过将您的页面更改为该网址来点击操作中的网址,因此如果您不想动态执行此操作,则必须在评论视图中处理重定向和呈现以返回到同一页面。
答案 1 :(得分:0)
我最后通过添加代码来处理相同视图中的注释,并将文章呈现为我的代码
def _article(request, article_id):
try:
article = Article.objects.get(pk=article_id)
related_articles = Article.objects.filter(tags=article.tags).exclude(pk=article.pk)[:4]
context['article'] = article
context['related_articles'] = related_articles
context['form'] = CommentForm()
if request.method == 'POST':
form = CommentForm(request.POST)
if form.is_valid():
comment = form.cleaned_data['comment']
article.comments_set.create(comment=comment)
return render(request,'blog/article.html', context)
except Exception as e:
#write error to file
return render(request,'blog/404.html')