Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
111 views
in Technique[技术] by (71.8m points)

python - Django RelatedObjectDoesNotExist at /HomeFeed/comments/slug-1

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You have no slufField in Comment's Model. AND you're trying to call slug which doesn't exist. First add slugField in Comment model. You have to create a new slugField for Comment Model

Then Try Again


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...