如何在Django的views.py中的一个类下显示模型和表单?

时间:2017-09-25 17:06:45

标签: python django django-models django-templates django-views

我正在尝试显示我将使用AgentForm获取的详细信息模板中的数据,并且我还尝试添加对每个代理程序唯一的Matrix1Form,并且该matrix1form将显示​​在details.html中。

这是我的views.py,如果我尝试显示Matrix1Form,代理模型中的数据不会显示,反之亦然,如果我想显示代理,我必须注释掉Matrix1Form。到目前为止没有出现任何错误。数据不会显示。

views.py

class AgentDetailsView(generic.DetailView):
    template_name = 'User/AgentDetails.html'

    class Meta:
        model = Agent

    def get(self, request, *args, **kwargs):
        matrix1form = Matrix1Form()
        return render(request, self.template_name, {'matrix1form':             
                                                     matrix1form})

forms.py

class AgentForm(forms.ModelForm):
    prefix = 'agentform'
    class Meta:
        model = Agent
        fields = '__all__'

class Matrix1Form(forms.ModelForm):
    prefix = 'matrix1form'
    class Meta:
        model = Matrix1
        fields = '__all__'

models.py

class Agent(models.Model):
    AgencyName = models.CharField(blank=True, max_length = 50,           
    verbose_name="Agency Name")
    OtherAgencyName = models.CharField(max_length=50, blank=True)
    FirstName = models.CharField(max_length=50, null=True)
    LastName = models.CharField(max_length=50, null=True)

details.html

    <ul>
    <li>AgencyName: {{agent.AgencyName}} </li>
    <li>OtherAgencyName: {{agent.OtherAgencyName}} </li>
    <li>First Name: {{agent.FirstName}} </li>
    <li>Last Name: {{agent.LastName}} </li>
    </ul>

    <form class="form-horizontal" action="" method="post"                 
    enctype="multipart/form-data">
    {% csrf_token %}
    <table>
    {{ matrix1form.as_table }}
    </table>
    </form>

1 个答案:

答案 0 :(得分:1)

如果我理解你的错误,你需要覆盖get_context_data,例如:

class AgentDetailsView(generic.DetailView):
    template_name = 'User/AgentDetails.html'

    class Meta:
        model = Agent

    def get_context_data(self, **kwargs):
        # ^^^^^^^^^^^^^^
        context = super(AgentDetailsView, self).get_context_data(**kwargs)
        matrix1form = Matrix1Form()
        context['matrix1form'] = matrix1form
        return context