Answer the question
In order to leave comments, you need to log in
Comments not showing under article on django site?
comments are sent to the database, but the site does not work, got confused in views
models.py
class Comment(models.Model):
post = models.ForeignKey('Post', verbose_name='Article', on_delete=models.CASCADE)
author = models. ForeignKey(User, verbose_name='User', on_delete=models.CASCADE)
message = models.CharField('Comment', max_length=150)
date = models.DateTimeField(auto_now_add=True, db_index=True, verbose_name='Published')
class Meta:
verbose_name = 'Comment'
verbose_name_plural = 'Comments'
def __str__(self):
len_title = 75
if len(self.message) > len_title:
titlestring = self.message[:len_title] + '...'
else:
titlestring = self.message
return titlestring
views.py
class PostCommentCreate(LoginRequiredMixin, CreateView):
model = Comment
template_name = 'blog/post_commentform.html'
fields = [ 'message', ]
def get_context_data(self, **kwargs):
context = super(PostCommentCreate, self).get_context_data(**kwargs)
context['post'] = get_object_or_404(Post, pk=self.kwargs['pk' ])
return context
def form_valid(self, form):
form.instance.author = self.request.user
form.instance.post = get_object_or_404(Post, pk=self.kwargs['pk'])
return super(PostCommentCreate, self).form_valid(form)
def get_success_url(self):
return reverse('blog_post', kwargs={' pk': self.kwargs['pk'], })
html
Comments
{% for comment in post.blogcomment_set.all %}
{{ comment.author }} ({{ comment.date }}) - {{ comment.message }}
{% endfor %}
{% if user.is_authenticated %}
Add new comment
{% else %}
Login Add comment
{% endif %}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question