在ListView中使用酥脆的表单

时间:2021-07-10 16:03:15

I am pretty new to Python and Django, but what I am trying to do is to use a Crispy Form in one of my template that is loaded with a ListView type of view. I usually load all of my other templates from a UpdateView which provide everything Crispy need already. I can't change the type of view here so I have to stick with the ListView but when I try to load the form, Crispy can't find it. I don't know how to provide the form to the template manually.

我对Python和Django非常陌生,但是我要做的是在我的一个模板中使用一个酥脆的表单,该模板装载了ListView类型的视图。我通常从UpdateView中加载所有其他模板,它已经提供了所有需要的脆皮。我不能改变这里的视图类型,所以我只能使用ListView,但是当我试图加载表单时,Crispy找不到它。我不知道如何手动将表单提供给模板。

Here is what I have so far:

以下是我目前所拥有的:

My template:

我的模板:

{% extends "base.html" %}
{% load crispy_forms_tags %}
{% load i18n %}
{% load tz %}

  {% block content %}

  {% crispy form %}

  <!-- template content -->      

  {% endblock %}

My form.py

我form.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")

My view.py:

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

Here is the error I get from Django when trying to access the page:

下面是我在试图访问这个页面时从Django得到的错误:

VariableDoesNotExist: Failed lookup for key [form] in u"[some other stuff]"

变量不存在:在u中查找键[表单]失败

1 个解决方案

#1


1  

In get_context_data create an instance of your form and add it to the context.

在get_context_data中,创建表单实例并将其添加到上下文。

def get_context_data(self, **kwargs):
    #some other stuff — where you create `context`

    context["form"] = UserBirthdayForm()

    return context

#1


1  

In get_context_data create an instance of your form and add it to the context.

在get_context_data中,创建表单实例并将其添加到上下文。

def get_context_data(self, **kwargs):
    #some other stuff — where you create `context`

    context["form"] = UserBirthdayForm()

    return context