Higure
Higure

Reputation: 235

Get an attribute in a template from a ManyToMany relationship in Django

In my Django 1.5 project I have a many-to-many relationship between two models:

class File(models.Model):
    #..
    subject = models.ManyToManyField(Subject)

class Subject(models.Model):
    subject = models.CharField(max_length = 30, primary_key=True, blank=False, null=False)

What I want to do is, knowing the file, access to the subject in my HTML templates.

Of course {{ file.subject }} doesn't work. I know that {{ file.subject.subject }} it's a query set that can be looped but, even if I try, I don't know how I can grab the right Subject object.

Is there a way to do it only from templates? Or it's best to pass it from the view?

Upvotes: 0

Views: 569

Answers (2)

Martijn Pieters
Martijn Pieters

Reputation: 1123410

There will be 0 or more subjects; if you just want to loop, do so with a for block over file.subject.all():

{% for subject in file.subject.all %}
    {{ subject.subject }}
{% empty %}
    Sorry, no subjects found.
{% endfor %}

If you need to find a specific subject, you'll have to query for it. Do so in the view; logic like this should be left to Python code:

subject = file.subject.filter(subject__startswith='Foo').first()

Upvotes: 1

ndpu
ndpu

Reputation: 22571

Try join template tag:

{{ file.subject.all|join:", " }}

or loop:

{% for subj in file.subject.all %}
     {{ subj }}<br/>
{% endfor %}

Upvotes: 2

Related Questions