Home > Software engineering >  Django Pass more complex python types into template
Django Pass more complex python types into template

Time:10-31

I'm creating a Car Shop web application using Django. Here is my index view:

def index(request):
    cars = Car.objects.filter(brand=request.user.preferred_brand)
    return TemplateResponse(request, "main/home.html", {"cars": cars})

This shows the list of all cars which currently authenticated user has set a preferrence for.

In my database, I also have the following model:

class Interest(models.Model):
    repair_company_name = models.CharField(max_length=200)
    car_id = models.IntegerField()

Each car has a set of companies that are willing to provide repair support for specific car. I would like to show this information on user's home page as well - so that he will not only see the list of his preferred cars, but each car will have information about repair companies next to it too.

Here comes my problem - how to pass such a complex type into django template, as I'm not able to do there complex operations like indexing or so. I could imagine creating something like dictionaries containing these information groupped (so that each dictionary would contain everything about car and also the list of strings of names of all repair companies that belong to it). But how to access such a dictionary and its values from template? Is there any better way to do this?

CodePudding user response:

You can access a complex dictionary in the template like this:

{{data.0}} // same as 'data[0]'
{{data.user_info}} // same as 'data["user_info"]'

// And you can chain these like this
{{data.0.user_info.id}}

CodePudding user response:

Its not complex as you think, there is no enough information about your models, however you can fulfill this requirement by:

In interest model you need to change"car_id" filed to be foreign key from Car model,so intrest model will be:

class Interest(models.Model):
    repair_company_name = models.CharField(max_length=200)
    car_id = models.ForeignKey(Car, on_delete=models.CASCADE, related_name="interest")

thereby you can get the list of interested repairs shops in this way:

from django.shortcuts import get_list_or_404    
cars = get_list_or_404(Car, brand=request.user.preferred_brand)  # assume that user can have many preferred brands
for each car in cars:
    car.inetrest.all()
  

regarding showing them in html page, you can use Listviews class or doing nested lists, using Listviewes is not complicated, all you need is to set the queryset in this way:

qs = inetrest.objects.filter(car_id=request.user.preferred_brand) 

of course this is high level explanation and would require some tweaking from your end

  • Related