我正在制作评论后的Web应用程序。在主页上,将显示各种帖子以及“答案/评论”按钮。单击它时,我需要显示要答复的帖子的内容以及评论表格。帖子和评论是单独的模型。
到目前为止,我已经在网上扫描了在同一页面上显示两个单独模型的方法。但是在这里,我需要使用“ GET”呈现帖子内容,它是pk和用于提交评论的表单,这是一种“ POST”方法。
这是我的模型。py:
class Post(models.Model):
pid = models.AutoField(primary_key=True)
title = models.CharField(max_length=1000)
content = RichTextUploadingField()
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('blog-home')#, kwargs={'pk':self.pk})
class Comment(models.Model):
cid = models.AutoField(primary_key=True)
author = models.ForeignKey(User, on_delete=models.CASCADE)
post = models.ForeignKey(Post, on_delete=models.CASCADE)
answer = RichTextUploadingField()
comment_date = models.DateTimeField(default=timezone.now)
def __str__(self):
return self.answer
def get_absolute_url(self):
return reverse('blog-home')
def save(self, *args, **kwargs):
super(Comment, self).save(*args, **kwargs)
我的views.py是这样的:
class PostDetailView(DetailView):
model = Post
class CommentCreateView(LoginRequiredMixin, CreateView):
model = Comment
fields = ['answer']
def form_valid(self, form, **kwargs):
form.instance.author = self.request.user
form.instance.post_id = self.kwargs['pk']
return super().form_valid(form)
两个网址-一个用于发布详细信息视图,另一个用于评论创建视图,如下所示:
path('post/<int:pk>/', PostDetailView.as_view(), name='post-detail'),
path('post/<int:pk>/comment/', CommentCreateView.as_view(), name='comment-create')
comment_form的模板如下:
% extends "blog/base.html" %}
{% load crispy_forms_tags %}
{% block extrahead %}
<script>window.CKEDITOR_BASEPATH = '/static/ckeditor/ckeditor/';</script>
{{ block.super }}
{% block detail %}
{% include "blog/post_detail.html" with pid="object.post_id" %}
{% endblock %}
{% block answer %}
<div class="content-section">
<form method="POST">
{% csrf_token %}
<fieldset class="form-group">
<legend class="border-bottom mb-4">
Answer</legend>
{{form.media}}
{{form|crispy}}
</fieldset>
<div class="form-group">
<button class="btn btn-outline-info", type="submit">Submit
</button>
</div>
</form>
</div>
{% endblock %}
{% endblock %}
单击“答案”按钮后,我希望以上两个URL都可以运行并在上半部分呈现后详细信息页面,并在单个页面的下半部分注释创建视图。任何指导都受到高度赞赏。