我希望在使用crispy-forms生成的布局时,能够与CreateView一起使用。然而,似乎我在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>
我还需要做什么才能使它工作?
{% crispy %}
而不是form | crispy
。请参考https://django-crispy-forms.readthedocs.io/en/latest/filters.html#using-crispy-tag-because-it-rocks - Zheng Liu