Ben2pop
Ben2pop

Reputation: 756

Retrieve data on a django templates

I am having trouble to understand the principles of retrieving data in template. I understand very well how to do it from the Shell. But I always block on how to do it using class based view. I have a simple view :

class ProjectDetailView(generic.DetailView, LoginRequiredMixin):
    #import pdb; pdb.set_trace()
    model = Project
    template_name = 'project_details.html'

so in my template I easily retrieve data from the model Project like {{project.name}} or {{project.team_id}}

But If I want I would like to show in my project detail data from other models, how can I do it ? Let assume I would like to show a list of all team members ?

here are my models:

class Team(models.Model):
    team_name = models.CharField(max_length=100, default = '')
    team_hr_admin = models.ForeignKey(MyUser, blank=True, null=True)
    members = models.ManyToManyField(MyUser, related_name="members")

    def __str__(self):
        return self.team_name


class Project(models.Model):
    name = models.CharField(max_length=250)
    team_id = models.ForeignKey(Team, blank=True, null=True)
    project_hr_admin = models.ForeignKey('registration.MyUser', blank=True, null=True)
    candidat_answers = models.ManyToManyField('survey.response')

Upvotes: 1

Views: 947

Answers (2)

Jahongir Rahmonov
Jahongir Rahmonov

Reputation: 13733

You should add extra data to your context, like this:

class ProjectDetailView(generic.DetailView, LoginRequiredMixin):
    model = Project
    template_name = 'project_details.html'

    def get_context_data(self, **kwargs):
        # Call the base implementation first to get a context
        context = super(ProjectDetailView, self).get_context_data(**kwargs)
        # Add in a QuerySet of all the team members
        context['members'] = self.get_object().team_id.members.all()
        return context

Then, in your template you will be able to show them like this:

{% for member in members %}
    {{ member.name }}   # or any other attribute
{% endfor %}

Hope it helps!

Upvotes: 0

Daniel Roseman
Daniel Roseman

Reputation: 599610

Normally you don't do queries in templates; you do them in the view, whether it's a class or function based view.

In this particular case though, since the data is linked via relationships, you can follow those relationships in the template:

Team: {{ project.team_id.name }}
Members: 
{% for member in project.team_id.members.all %}
    {{ member.name }}
{% endfor %}

Data that isn't linked in that way can be added to the context by overriding the get_context_data method in your view.

Upvotes: 1

Related Questions