我是 Python 和 Django 的新手,但我想做的是在我的一个加载了 ListView 类型 View 的模板中使用 Crispy Form。我通常从 UpdateView 加载所有其他模板,它已经提供了 Crispy 需要的一切。我不能在这里更改 View 类型,所以我必须坚持使用 ListView,但是当我尝试加载表单时,Crispy 找不到它。我不知道如何手动将表单提供给模板。
这是我目前所拥有的:
我的模板:
{% extends "base.html" %}
{% load crispy_forms_tags %}
{% load i18n %}
{% load tz %}
{% block content %}
{% crispy form %}
<!-- template content -->
{% endblock %}
我的表格.py
class UserBirthdayForm(forms.ModelForm):
birth_day = forms.IntegerField(required=True, localize=True, label=_('*My birth day'))
birth_month = forms.IntegerField(required=True, localize=True, label=_('*My birth month'))
birth_year = forms.IntegerField(required=True, localize=True, label=_('*My birth year'))
def __init__(self, *args, **kwargs):
super(UserForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.layout = Layout(
Div(
Div('birth_day', css_class='col-sm-4'),
Div('birth_month', css_class='col-sm-4'),
Div('birth_year', css_class='col-sm-4'),
css_class='row'
),
Submit('save', _('update'), css_class='pull-right'),
)
class Meta():
model = User
fields = ("birth_day", "birth_month", "birth_year")
我的 View .py:
class MissionList(LoginRequiredMixin, ListView):
form_class = UserBirthdayForm
def get_queryset(self):
#some other stuff
return queryset
def get_context_data(self, **kwargs):
#some other stuff
return context
这是我在尝试访问页面时从 Django 得到的错误:
VariableDoesNotExist:在 u[some other stuff] 中查找键 [form] 失败
请您参考如下方法:
在 get_context_data 中创建一个表单实例并将其添加到上下文中。
def get_context_data(self, **kwargs):
#some other stuff — where you create `context`
context["form"] = UserBirthdayForm()
return context
