What would be the best approch to display a commenting form in the ListView for each blog post?

Viewed 33

I currently have fully functional commenting form in my blog post view that I want to display in the ListView. Sort of like linkedin has under every list item, if you have noticed, i think facebook has the same thing.

Is there a shortcut to achieve this?

1 Answers

I supposed you can combine a ListView with a FormMixin (https://docs.djangoproject.com/fr/4.1/ref/class-based-views/mixins-editing/#django.views.generic.edit.ModelFormMixin)

In each item of list, you create your form html and checking if form exist and if form instance corresponds to current list view for displaying errors and data in case of invalid form sent.

class MyPostList(FormMixin, ListView);
    model = Post
    form = CommentAddForm
    template...


class CommentAddForm(ModelForm):

    class Meta:
        model = Comment
        fields = ('post_id', 'txt'...)

{% for post in post_list %}
    {{post}}

    <form>
        {% if form.data.post_id == post.pk %}{{form.errors}}{% endif %}
        <input type="hidden" name="post_id" value="{{post.pk}}" />
    </form>

{% endfor %}
Related