Django: Class based view can't render crispy form

耗尽温柔 提交于 2019-12-24 01:00:01

问题


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.


回答1:


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




回答2:


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.




回答3:


What bit me was I left

{{ form|crispy }}

instead of using

% crispy form %}

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



来源:https://stackoverflow.com/questions/12052420/django-class-based-view-cant-render-crispy-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!