【发布时间】:2021-04-29 17:24:46
【问题描述】:
我的详细信息和创建视图正在工作,但在帖子下添加评论后我无法重定向到同一页面...
我想从我的 CommentForm 中删除“帖子”字段,以便我将评论保存到帖子对象,而无需用户选择要保存到的帖子 // 我为评论的作者做了同样的事情,但不能为帖子本身做同样的事情
我的观点
class PostDetailView(DetailView):
model = Post
template_name='blog/post_detail.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
comments = Comment.objects.filter(post=self.object)
context['comments'] = comments
context['form'] = AddCommentForm()
return context
class CommentCreateView(CreateView):
model = Comment
fields = ['content','post']
template_name = 'blog/post_detail.html'
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
我的模型
class Post(models.Model):
options = (
('draft', 'Draft'),
('published', 'Published')
)
title = models.CharField(max_length=250)
slug = models.SlugField(max_length=250, unique_for_date='publish_date')
publish_date = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts')
content = models.TextField()
status = models.CharField(max_length=10, choices=options, default='draft')
class Meta:
ordering = ('-publish_date',)
def __str__(self):
return self.title
class Comment(models.Model):
post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments')
author = models.ForeignKey(User, on_delete=models.CASCADE)
content = models.TextField()
publish_date = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ('-publish_date',)
def __str__(self):
return f'Comment By {self.author}/{self.post}'
def get_absolute_url(self):
return reverse('post-detail', kwargs={'pk':self.post.pk})
我的表格
class AddCommentForm(forms.ModelForm):
content = forms.CharField(label ="", widget = forms.Textarea(
attrs ={
'class':'form-control',
'placeholder':'Comment here !',
'rows':4,
'cols':50
}))
class Meta:
model = Comment
fields =['content','post']
html表单
<form action="{% url 'blog:comment-update' object.id%}" method="POST">
<div class="col-12">
<hr>
{% with comments.count as total_comments %}
<legend class="border-bottom mb-4">{{total_comments }} comment{{total_comments|pluralize }}</legend>
{% endwith %}
{% for c in comments%}
<div class ="col-md-12 mb-1rem" >
<p class="mb-0"><strong>{{c.author}}:</strong> {{c.content}}</p>
<small class="text-muted">{{ c.publish_date|date:'f A, Y'}}</small>
</div>
<br>
{% endfor %}
</div>
<hr>
{% csrf_token %}
<fieldset class="form-group">
<legend class="border-bottom mb-4">New Comment</legend>
{{ form|crispy }}
</fieldset>
<div class="form-group">
<button class="btn btn-dark btn-lg mt-1" type="submit">Publish</button>
</div>
</form>
网址
urlpatterns = [
path('', views.PostListView.as_view(), name='blog-home'),
path('blog/<int:pk>/', views.PostDetailView.as_view(), name='post-detail'),
path('blog/<int:pk>/update', views.CommentCreateView.as_view() , name='comment-update'),
]
【问题讨论】:
标签: django django-models django-views django-forms django-templates