user6140865
user6140865

Reputation:

Combining model data to form url pattern

I am generating a generic list right now, with the following code:

views.py

class ServiceReportIndex(LoginRequiredMixin, ListView):
    model = TblServiceRecords
    context_object_name = 'all_servicereports'
    login_url = 'login'
    template_name = 'servicereport/servicereport_index.html'

    def get_context_data(self, **kwargs):
        context = super(ServiceReportIndex, self).get_context_data(**kwargs)
        context['companies'] = TblCompanies.objects.all()
        return context

In my template, I want to generate a URL using both of the models. The TblServiceRecords model contains a column that references the company_id, which is the primary key of the appropriate company in the TblCompanies model. I want to use the company_name from the Companies model in my list view. How would I go about doing that? I'm sure it's simple but I can't seem to get my url tags done correctly.

                <div class="col-sm-4">
                  <p>Company Name</p>
                    {% for servicereport in all_servicereports %}
                    <p><a href="{% url 'servicereport:servicereport_detail' servicereport.sr_id %}">{% for servicereport.company_id in companies.company_id %} {{ companies.company_name }} {% endfor %}</a></p>
                    {% endfor %}
                </div>

Also, how can I be sure my views.py is set up correctly for multiple model functionality? I ask because if I put

            {% for company_name in companies %}
                {{companies.company_name}}
            {% endfor %}

In my template, nothing comes up, but there are no errors either.

Upvotes: 0

Views: 30

Answers (1)

neverwalkaloner
neverwalkaloner

Reputation: 47364

Probably you cannot see companies bacause of this:

{{companies.company_name}}

companies is queryset and it does not have company_name property.

Try this:

{% for company_name in companies %}
    {{company_name.company_name}}
{% endfor %} 

Upvotes: 2

Related Questions