I have the following model:
class Log(models.Model):
log_order = models.IntegerField(validators=[MinValueValidator(1)],blank=True, null=True)
class ActiveSession(models.Model):
log = models.ManyToManyField(Log, related_name='savedlogs')
In my view I am trying to get the very last create ActiveSession which has a many to many relationship with Log model to iterate between them.
This is how I created the views:
def get_context_data(self, **kwargs):
active_session =ActiveSession.objects.get(id=ActiveSession.objects.last().id)
context = super().get_context_data(**kwargs)
return context
I think my problem is with the get i tried using filter(id=id).latest but it did not work.
here is the template:
{% for x in active_session %}
{{ x.log_order }}
{% endfor %}
I am currently getting TypeError: 'ActiveSession' object is not iterable
my question:
How to fix this error and how can I use the for loop in the template to display the details of each Log which is inside each ActiveSession.
In this example there are 3 Logs inside the Active session and I want to show the log_order of each
CodePudding user response:
You should pass the single ActiveSession object to the template and then iterate though the log instance associated with the session.
class FooView(generic.View):
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context["active_session"] = ActiveSession.objects.last()
return context
# template.html
{% for log in active_session.log.all %}
{{ log }}
{% endfor %}
