How to use CreateView with crispy-forms in Django

2019-07-07 07:41发布

问题:

I want to use CreateView along with crispy-forms generated layout. However, it seems that everything I pass to self.helper in forms.py is ignored. Form renders nicely, but only with fields generated by CreateView - all fields passed to Layout are missing.

My views.py

class MyView(CreateView):
    form_class = MyForm
    model = MyModel

    def form_valid(self, form):
        pass

My forms.py:

from django.forms import ModelForm, Textarea
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit, Layout
from crispy_forms.bootstrap import FormActions

from .models import MyModel

class MyForm(ModelForm): 

    def __init__(self, *args, **kwargs):
        super(MyForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper(self)
        self.helper.form_method = 'POST'
        self.helper.add_input(Submit('submit', 'Submit'))
        self.helper.layout = Layout( 
            FormActions(Submit('BlahBlah', 'BlahBlah', css_class='btn-primary')))

    class Meta:
        model = MyModel
        fields = ['xxx', 'yyy']

My image_form.html:

{% load crispy_forms_tags %}
...
<form action="" method="post" enctype="multipart/form-data">
    {% csrf_token %}
    {{ form|crispy }}
</form>

What else should I do to make it work?

回答1:

I have done it similar to @user3316785

My CreateView looks like:

class CreateDoktrinView(CreateView):
   model = Doktrin
   fields = ['name', 'description']

   def get_form(self, form_class=None):
       form = super().get_form(form_class)
       form.helper = FormHelper()
       form.helper.add_input(Submit('submit', 'Create', css_class='btn-primary'))
       return form

and in the template I can simply use:

 {% crispy form %}


回答2:

I've solved this differently.

I've updated MyView in the following way:

from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit

class MyView(CreateView):
    form_class = MyForm
    model = MyModel
    helper=None

    def form_valid(self, form):
        pass
    def __init__(self, *args, **kwargs):
        super(MyView, self).__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.form_id = 'id-exampleForm'
        self.helper.form_class = 'blueForms'
        self.helper.form_method = 'post'
        self.helper.form_action = 'url_action_call'
        self.helper.add_input(Submit('submit', 'Save', css_class='btn-primary'))

    def get_context_data(self, **kwargs):
        context = super(MyView, self).get_context_data(**kwargs)
        context['helper'] = self.helper
        return context

This will give you the whole form with the crispy tag in your template by adding:

{% load crispy_forms_tags  %}
{% crispy form helper %}


回答3:

Got answer at: https://groups.google.com/forum/#!topic/django-users/Ovp_FgL3YwY

Had to change

{{ form|crispy }}

to

{% crispy form %}