其他分享
首页 > 其他分享> > 如何在Django中使用带有crispy-forms的CreateView

如何在Django中使用带有crispy-forms的CreateView

作者:互联网

我想使用CreateView以及crispy-forms生成的布局.但是,我似乎忽略了传递给forms.py中self.helper的所有内容.
表单渲染很好,但只有CreateView生成的字段 – 缺少传递给Layout的所有字段.

我的views.py

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

    def form_valid(self, form):
        pass

我的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']

我的image_form.html:

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

我还应该做些什么才能让它发挥作用?

解决方法:

我做的类似于@ user3316785

我的CreateView看起来像:

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

在模板中我可以简单地使用:

 {% crispy form %}

标签:django-crispy-forms,python,django
来源: https://codeday.me/bug/20190725/1530631.html