简体   繁体   中英

How to Create a Comment Model for Posts in a Django Project

I am new in creating projects using Django, so I am creating a Blog Project, I am trying to add a comment function for my posts, I have created a Class Based View for the comments.

I have also tried 2 comments as a trial from the admin and they are showing perfectly. My only issue is that I can not view the form from the website.

I am not sure what I have missed?

Here is the models.py

class Comment(models.Model):
    # To know Who liked
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    post = models.ForeignKey(Post, on_delete=models.CASCADE)
    body = models.TextField(max_length=300)
    updated = models.DateTimeField(auto_now=True)
    created = models.DateTimeField(auto_now=True)

    def __str__(self):
        return f"{self.post}-{self.user}-Comment No.{self.pk}"

Here is the views:

class Comment_create(CreateView):
    model = Comment
    fields = ['body']  
    template_name = 'blog/post_detail.html'
    form_class = CommentModelForm

    def form_valid(self, form):
        form.instance.user = self.request.user
        return super().form_valid(form)

Here is the forms.py

class CommentModelForm(forms.ModelForm):
    body = forms.CharField(label='',
                            widget=forms.TextInput(attrs={'placeholder': 'Add a comment...'}))
    class Meta:
        model = Comment
        fields = ('body',)

Here is the urls.py

    path('blogs/comment', Comment_create.as_view(), name='comment-post'),

Here is the template:

        <h2>Comments...</h2>
                {% if not post.comment_set.all %}
                  No comments yet
                {% else %}
                    {% for c in post.comment_set.all %}

                        <div class="ui segment mb-5">
                            <span>{{ c.user }} {{ c.created }}</span>
                            <div class='mt-5'>{{ c.body }}</div>
                        </div>
                    {% endfor %}
                {% endif %}
                <form action="" method="POST" class='ui fluid form'>
                    {% csrf_token %}
                      {{ form }}
                    <button type="submit" class="ui primary button mt-5 w-full">Comment</button>
                </form>

Please have a look at django-comments-xtd package. I think everything that you need will be available in this package.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM