Sukhrab
Sukhrab

Reputation: 95

How can I display a model and a form under one class in views.py in Django?

I am trying to display the data in details template that I would obtain using AgentForm and I am also trying to add a Matrix1Form that will be unique to each agent, and that matrix1form would be displayed in details.html.

Here is my views.py and if I try to display the Matrix1Form, the data from Agent model doesn't get displayed and vice versa, if I want to display an agent, I have to comment out the Matrix1Form. There are no errors popping up so far. The data just don't get displayed.

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>

Upvotes: 0

Views: 75

Answers (1)

user8060120
user8060120

Reputation:

if i understand you correct, you need to override get_context_data for example:

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

Upvotes: 1

Related Questions