Is it possible to have a form in a ListView template?

限于喜欢 提交于 2019-12-01 13:38:30

Yes, but all the form process will have to be made by the ListView itself. That is simple, considering you can inherit the behaviour from ModelFormMixin. You will only need one url (to the list view). The template will look like:

{% if user.is_authenticated %}
<form action="" method="POST">
    {% csrf_token %}
    {{ form }}
    <input type='submit' value='POST'/>
</form>
{% endif %}

And your view:

from django.views.generic.list import ListView
from django.views.generic.edit import ModelFormMixin

class ListWithForm(ListView, ModelFormMixin):
    model = MyModel
    form_class = MyModelForm

    def get(self, request, *args, **kwargs):
        self.object = None
        self.form = self.get_form(self.form_class)
        # Explicitly states what get to call:
        return ListView.get(self, request, *args, **kwargs)

    def post(self, request, *args, **kwargs):
        # When the form is submitted, it will enter here
        self.object = None
        self.form = self.get_form(self.form_class)

        if self.form.is_valid():
            self.object = self.form.save()
            # Here ou may consider creating a new instance of form_class(),
            # so that the form will come clean.

        # Whether the form validates or not, the view will be rendered by get()
        return self.get(request, *args, **kwargs)

    def get_context_data(self, *args, **kwargs):
        # Just include the form
        context = super(ListWithForm, self).get_context_data(*args, **kwargs)
        context['form'] = self.form
        return context
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!