Modelesq
Modelesq

Reputation: 5402

Loop through a manytomany field and return a template tag

Trying loop through the presenters field for an event. And then mark them as a presenter within the template with is_presenter.

I guess my question is: How do I properly loop through the manytomanyfield to return the template tag?

model

class Event(model.Model):
    title = models.CharField(max_length=200)
    presenters = models.ManyToManyField(Profile, null=True, blank=True)
    ...

view

for presenter in event.presenters_set.all():
    is_presenter = True

Thanks for you help in advance.

Upvotes: 0

Views: 2559

Answers (1)

dm03514
dm03514

Reputation: 55972

Its not quite clear what you are trying to accomplish. If you are doing this check in the template You could do something like

{% for presenter in event.presenters.all %}
   {% if presenter.is_presenter %}
     {% # format or do whatever it is you want to do to the presenter here %}
   {% else %}
     {% # this is not a presenter leave alone %}
   {% endif %}
{% endfor %}

If your checking presenter is any more complicated then something like above it would be good to keep it in your view instead of in your template. You could calculate which pressenters are actually presenting, put a flag on the presenter object and pass it to your template.

Upvotes: 6

Related Questions