Question

Hi Stackoverflow people,

I have trouble to render a crispy form with a class based view. Everything worked fine when I used the function based views.

As usual I generate forms.py as follows:

from django import forms    
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, Div, Submit, HTML, Button, Row, Field
from item.models import Item

class CreateItemForm(forms.ModelForm):
    class Meta:
        model = Item
        exclude = ('user',)

        def __init__(self, *args, **kwargs):
            self.helper = FormHelper()
            self.helper.form_tag = False
            self.helper.form_class = 'form-horizontal'
            self.helper.layout = Layout(
                Fieldset(
                    'Create your item here',
                    'name', 'description', 
                    'save',
                ),
            )
            self.request = kwargs.pop('request', None)
            return super(CreateItemForm, self).__init__(*args, **kwargs)

The view function is very simple and standard:

from django.views.generic.edit import CreateView,
from item.models import Item
from item.forms import CreateItemForm

class ItemCreate(CreateView):
    form_class = CreateItemForm
    model = Item
    template_name = 'item/item_create_form.html' 

and the template follows the minimal instructions as well:

{% extends "base.html" %}
{% load crispy_forms_tags %}
{% block content %}
<h2>Create new Item</h2>
            <form action="." class="crispy form-horizontal" method="post">
                {% crispy form form.helper %}
            </form>
{% endblock %}

My problem is that Django will complain "VariableDoesNotExist at /item/add/, Failed lookup for key [helper] in ...".

Are crispy forms compatible with class based views? How could I hand over the helper information to create the form correctly?

Thank you for your help and suggestions.

Was it helpful?

Solution

constructor in your form is too indented, this way it belongs to form's Meta class, but it should be directly in CreateItemForm

OTHER TIPS

use this instead of showing exclude

fields ('field1','field2','field3')

here replace field1 and field2 and field3 with your field names. which you wanna show.this works for me.

What bit me was I left

{{ form|crispy }}

instead of using

% crispy form %}

The former will only emit Django's generic class based views

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top