Search code examples
django-modelsdjango-querysetdjango-model-field

Django 2 - quieres in HTML


I am creating a program to list all main locations for a selected engagement. I have two models: Engagement and MainLocation. Engagement is a foreign key in the MainLocation model. The main location model looks like this:

class MainLocation(models.Model):
    loc_name = models.CharField(max_length=256)
    engagement = models.ForeignKey(Engagement,related_name='main_location', on_delete="Cascade")

To view all the main locations in the respective engagement I have this in my HTML:

Main Locations for {{engagement.engagement_name}}
    <ul>
      {% for location in engagement.main_location.all %}
        <li>{{mainlocation.loc_name}} </li>
      {% endfor %}
    </ul>

This will get me the correct engagement name and give me the correct amount of locations in the unordered list. So I know that it is counting the right amount of location. I am confused why the name of each location is not being displayed. I have also tried:

{{engagement.main_location.loc_name}}
{{engagement.main_location.id}}

Am I missing something in the syntax? Any help would be appreciated.


Solution

  • Found the issue. SO apparently when using the DetailView in Django you have to put the module name in the for loop. This will give you access to the module.

    Like this:

    Main Locations for {{engagement.engagement_name}}
        <ul>
          {% for mainlocation in engagement.main_location.all %}
            <li>{{mainlocation.loc_name}} </li>
          {% endfor %}
        </ul>