简体   繁体   中英

How to add comments on Python Django posts with logged in username?

Please let me know that where i am making mistake? views.py

class AddComment(LoginRequiredMixin, CreateView):

    model = Comment
    form_class = CommentForm
    template_name = 'comment.html'

    success_url = reverse_lazy('home')

    def form_valid(self, form):
        form.instance.name = self.request.user
        form.instance.post_id = self.kwargs\['pk'\]
        return super().form_valid(form)

Are these forms written correctly? forms.py class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('body', )

        widgets = {
            # 'name': forms.TextInput(attrs={'class': 'form-control'}),
            'body': forms.Textarea(attrs={'class': 'form-control'}),
        }

Should I make any changes in models? models.py

class Comment(models.Model):
    post = models.ForeignKey(Post,
                             related_name='comments',
                             on_delete=models.CASCADE)
    name = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
    )
    body = models.TextField(max_length=240)
    date_added = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return '%s - %s' % (self.post.title, self.name)

This is comment section for letting user to comment on post with showing its own name? comments.html

{% if not object.comments.all %}
    <p>No comments yet...</p>
    <a href="{% url 'comment' object.pk %}">Add one</a>
    {% else %}
    <a href="{% url 'comment' object.pk %}">Add Comment</a>
    <br><br>
    {% for comment in object.comments.all %}
    <strong>{{ comment.name }} </strong> - <small>{{ comment.date_added }}</small>
    <br>
    {{ comment.body }}
    <br><br>
    <hr>
    {% endfor %}
    {% endif %}

Here is the urls of AddComment class view. urls.py

path('post/<int:pk>/comment/', AddComment.as_view(), name='comment'),][1]

You did not state clearly what has gone wrong with your code. I would like to give some suggestions. First of all,

{% for comment in object.comments.all %}
   ...
{% endfor %}

You are putting this block of code inside {% if not object.comments.all %}...{% endif %} so it will not show on template if the comment section is not empty.

Also, this link:

<a href="{% url 'comment' object.pk %}">Add Comment</a>

should open a Django template form , where user can actually fill in the comment. After that, on POST request of the form, it will send comment data to the URL you put in action param of the form, as below:

<form action="{% url 'comment' post.pk %}" method="post">
[Comment code here]
</form>

which will link to this URL you provided:

path('post/<int:pk>/comment/', AddComment.as_view(), name='comment'),]

It will be better if you can provide your code in views.py as well to make it easier to track down where it goes wrong.

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