我正试图从博客页面调用我的评论表单,但它只会不断刷新特定的博客页面。这是我的代码;
models.py
class BlogPost(models.Model):
# id = models.IntegerField()
user = models.ForeignKey(User, default=1, null=True, on_delete=models.SET_NULL)
image = models.ImageField(upload_to='image/', blank=True, null=True)
title = models.CharField(max_length=120)
slug = models.SlugField(unique=True)
content = models.TextField(null=True, blank=True)
publish_date = models.DateTimeField(auto_now=False, auto_now_add=False, null=True, blank=True)
timestamp = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
objects = BlogPostManager()
class Meta:
ordering = ['-publish_date', '-updated', '-timestamp']
def __str__(self):
return self.title
def get_absolute_url(self):
return f"/blog/{self.slug}"
def get_edit_url(self):
return f"{self.get_absolute_url()}/edit"
def get_delete_url(self):
return f"{self.get_absolute_url()}/delete"
class Comment(models.Model):
comment_cont = models.TextField(max_length=200, verbose_name='Comment content')
user_name = models.ForeignKey(User, default=1, null=True, on_delete=models.SET_NULL)
comment_post = models.ForeignKey(BlogPost, on_delete=models.CASCADE, related_name='comments')
comment_date = models.DateTimeField(default=timezone.now)
def __str__(self):
return self.comment_cont
def get_absolute_url(self):
return f"{BlogPost.get_absolute_url()}"
def get_add_url(self):
return f"{self.get_absolute_url()}/addc"
views.py
def add_comment_to_post(request, slug):
post = get_object_or_404(BlogPost, slug=slug)
if request.method == "POST":
form = CommentForm(request.POST)
if form.is_valid():
comment = form.save(commit=False)
comment.post = post
comment.save()
return redirect('blog_post_detail_view', slug=post.slug)
else:
form = CommentForm()
template_name = 'formc.html'
context = {"title": f"New comment on {post.title}", "form": form}
return render(request, template_name, context)
urls.py
path('<str:slug>/addc', add_comment_to_post),
formc.html
<form method='POST' action='.' enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Comment</button>
</form>
home.html中的按钮
<a class="btn btn-primary" href="{{ comments.get_add_url }}">Add Comment...</a>
我知道该按钮的href
是不正确的,但是我不知道如何将其称为注释表单。拜托,我需要帮助。谢谢。
答案 0 :(得分:0)
我知道了href可能是什么。我有点觉得我是故意让我自己解决这个问题的。
请告诉我是否有更好的方法可以做到这一点。谢谢!
home.html
<a class="btn btn-primary" href="/{{blog_post.slug}}/addc/">Add Comment...</a>