znawca
znawca

Reputation: 279

How to display in template data from model?

Hi I Have two models:

class Country(models.Model):
    name = models.CharField(max_length=50)

class City(models.Model):
    name = models.CharField(max_length=50)
    country = models.ManyToManyField(Country)

Now I want display in template name and country every city, but when I do it:

{% for city in cities %}
    {{ city.name }}
    {{ city.country | linebreaks }}
{% endfor %}

I get this:

London 
city.Country.None 

Berlin 
city.Country.None 

Paris 
city.Country.None

What must i change?

views:

def city_list(request):
    cities = City.objects.all().order_by('name')
    return render(request, 'city/city_list.html', {'cities': cities})

EDIT: I changed in template city.country on city.country.name but I only get this:

London 
None 

Berlin 
None 

Paris 
None

I don't know how change "none" on country name.

Second problem: i want display every city which belongs to country.

def England(request):
    cities = City.objects.filter(country__name__exact="England").order_by('-name')
    return render(request, 'city/city_list.html', {'cities': cities})

It works but I want that it will display automatically for every country, I don't want create one view to one country.

I created view which directs to country detail but how display cities which are placed in this country?

def country_detail(request, pk):
    country = get_object_or_404(Country, pk=pk)
    return render(request, 'city/country_detail.html', {'country': country})

Upvotes: 2

Views: 142

Answers (1)

Pierre Criulanscy
Pierre Criulanscy

Reputation: 8686

Your City model has a ManyToMany relation to Country Model. So in your template city.country refers to the django built in manager for related data. You need to loop over it :

{% for city in cities %}
    {% for country in city.country.all %}
        {{ city.name }}
        {{ country.name | linebreaks }}
    {% endfor %}
{% endfor %}

In fact I think you should have a ForeignKey relation instead of ManyToMany because your Country model have many Cities but Cities only have one Country. So your final code should be the following :

class Country(models.Model):
    name = models.CharField(max_length=50)

class City(models.Model):
    name = models.CharField(max_length=50)
    country = models.ForeignKey(Country)

and your initial template code :

{% for city in cities %}
     {{ city.name }}
     {{ city.country | linebreaks }}
{% endfor %}

EDIT :

If you want to display all cities belonging to one Country django provides a related manager, so you can use :

country.city_set.all()

Or you can use a related_name in your model for you ForeignKey such as :

class City(models.Model):
    name = models.CharField(max_length=50)
    country = models.ForeignKey(Country, related_name="cities")

So you can now use :

country.cities.all()

Upvotes: 4

Related Questions