I decided to add a "comments" functionality for anyone to post comments on anyone's post. Everything works except one line of code which is giving me the problem.
I receive the following error:
RelatedObjectDoesNotExist at /HomeFeed/comments/slug-1
Comment has no post.
The error is directed to the views.py Specifically this line of code:
form.instance.post.slug = self.kwargs['slug']
How this code can be altered to remove the error?
views.py
class AddCommentView(CreateView):
model = 'Comment'
form_class = CommentForm
template_name = 'HomeFeed/add_comment.html'
def form_valid(self, form):
form.instance.post.slug = self.kwargs['slug']
return super().form_valid(form)
success_url =reverse_lazy('main')
urls.py
path('comments/<slug>', AddCommentView.as_view(), name= "add_comment"),
forms.py
class CommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = ['name', 'body']
widgets = {
'name' : forms.TextInput(attrs={'class': 'form-control'}),
'body' : forms.Textarea(attrs={'class': 'form-control'}),
}
models.py
class BlogPost(models.Model):
chief_title = models.CharField(max_length=50, null=False, blank=False)
body = models.TextField(max_length=5000, null=False, blank=False)
likes = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='blog_posts', blank=True)
author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
slug = models.SlugField(blank=True, unique=True)
date_published = models.DateTimeField(auto_now_add=True, verbose_name="date published")
def __str__(self):
return self.chief_title
def total_likes(self):
return self.likes.count()
class Comment(models.Model):
post = models.ForeignKey(BlogPost, related_name='comments', on_delete=models.CASCADE)
name = models.CharField(max_length=255)
body = models.TextField()
date_added = models.DateField(auto_now_add=True)
def __str__(self):
return '%s - %s' %(self.post.chief_title, self.name)
add_comment.html
(this html is for ppl to add their comments)
<div class="form-group">
<form method="POST"> {% csrf_token %}
{{ form.as_p }}
<button class="btn btn-secondary">Add Comment</button>
</form>
</div>
detail_blog.html
this is for ppl to see the comments
{% if not blog_post.comments.all %}
<p>No comments yet... Add a <a href="{% url 'HomeFeed:add_comment' blog_post.slug %}">comment</a></p>
{% else %}
<a href="{% url 'HomeFeed:add_comment' blog_post.slug %}">Add a comment</a>
<br>
{% for comment in blog_post.comments.all %}
<strong>
{{ comment.name}}
{{ comment.date_added }}
</strong>
<br>
{{ comment.body }}
{% endfor %}
{% endif %}
question from:
https://stackoverflow.com/questions/65649978/django-relatedobjectdoesnotexist-at-homefeed-comments-slug-1