在django中的DetailView中显示其他表单

时间:2017-07-08 11:27:14

标签: django

我在views.py

中有详细视图“part”
class part_detail_view(DetailView):
    model = part_list
    context_object_name = 'part_detail'
    template_name = 'part_detail.html'

    def get_context_data(self, **kwargs):
        context = super(part_detail_view, self).get_context_data(**kwargs)
        context['my_list'] = populate_nav_bar()
        return context

但是在这个URL里面我还想显示另一个库存模型的“CreateView”表格,这样我就可以在同一页面上显示表格来添加零件库存并添加库存。这在基于函数的视图中很容易完成,但我不确定如何在基于类的视图中执行此操作。

1 个答案:

答案 0 :(得分:2)

您必须在forms.py中明确编写表单:

# forms.py
class ParForm(forms.ModelForm):
    class Meta:
        model = Part  # Your Part model
        fields = '__all__'

然后将表单注入get_context_data()中的上下文:

# views.py
class PartDetailView(DetailView):
    ...

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['part_form'] = PartForm()  # Your part form
        return context

然后在模板中渲染表单:

...
<form method="post" action="{% url 'create_part' %}">
    {{ part_form }}
    <button type="submit">Submit</button>
</form>
...

其中create_part是您的CreateView的网址。