【问题标题】:Why can't I inject form into HTML?为什么我不能将表单注入 HTML?
【发布时间】:2020-05-01 04:08:41
【问题描述】:

我有一个表单,我想将它注入到基于类的 DetailView 中。

forms.py

class PastLocationForm(forms.Form):
    locations = forms.ModelChoiceField(queryset=Location.objects.all().order_by('location_name'))

views.py

class PatientDetailView(DetailView):
    model=Patient
    form_class = PastLocationForm

很遗憾,PastLocationForm 表单在注入后没有出现在 HTML 页面上。我检查了页面,什么都没有。

有趣的是,如果我将 PastLocationForm 传递给功能视图并将其呈现给另一个页面,表单就会显示出来!我还有其他视图,我将“form_class”用于其他 modelForms,它们可以正常工作。

如果找不到解决方案,我会将视图切换到功能视图,但我宁愿保留基于类的视图。

【问题讨论】:

    标签: django


    【解决方案1】:

    原因可能是 DetailView 不处理 form_class 属性(FormViews 可以),您需要使用 mixin。

    看看这个答案:

    Django combine DetailView and FormView

    【讨论】:

    • 这是一个有趣的方法。我自己永远不会想到它
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-23
    • 1970-01-01
    • 2022-09-25
    • 1970-01-01
    • 2021-02-13
    • 2016-05-15
    • 2011-02-09
    相关资源
    最近更新 更多