I am getting a error: everse for 'genre' with arguments '('',)' not found. 1 pattern(s) tried: ['genres/(?P<genre_id>[0-9]+)\\Z']
am trying to run a Django site but have a error when i click on this url:
'book:genres'
this is the error: Reverse for 'genre' with arguments '('',)' not found. 1 pattern(s) tried: ['genres/(?P<genre_id>[0-9]+)\Z'] something is wrong with this url:
<a href="{% url 'book:genre' genre.id %}">
my models page:
from django.db import models
# Create your models here.
class Genre(models.Model):
"""A Genre of a book"""
text = models.CharField(max_length=20)
date_added = models.DateTimeField(auto_now=True)
def __str__(self):
"""return a string representation of the model"""
return self.text
class Title(models.Model):
"""A Title of a book"""
genre = models.ForeignKey(Genre, on_delete=models.CASCADE)
text = models.CharField(max_length=20)
date_added = models.DateTimeField(auto_now=True)
class Meta:
verbose_name_plural = 'titles'
def __str__(self):
""""Return a string rep of model"""
return f"{self.text[:50]}"
my veiws:
from django.shortcuts import render
# Create your views here.
from .models import Genre
def index(request):
"""Home page"""
return render(request, 'book/index.html')
def genres(request):
genres = Genre.objects.order_by('date_added')
context = {'genres': genres}
return render(request, 'book/genres.html', context)
def genre(request, genre_id):
genre = Genre.objects.get(id=genre_id)
titles = genre.entry_set.order_by('-date_added')
context = {'genre': genre, 'titles':titles}
return render(request, 'book/genre.html', context)
my urls:
"""Defines url patterns for book app"""
from django.urls import path
from . import views
app_name = 'book'
urlpatterns = [
# Home page
path('', views.index, name = 'index'),
path('genres/', views.genres, name="genres"),
path('genres/<int:genre_id>', views.genre, name='genre'),
]
template genres.html:
{% extends 'book/base.html' %}
{% block content %}
<p>Genres</p>
<ul>
{% for i in genres %}
<li>
<a href="{% url 'book:genre' genre.id %}">
{{ i }}
</li>
</a>
{% empty %}
<li>No Genres available.</li>
{% endfor %}
</ul>
please help!!!!! Thank you sooo much!!!
{% endblock content %}
tried to use foreign key object to load page with a genre and all the titles.
You're using the variable i
in your genres.html, but then genre.id
will not have any value. Replace i
with genre
:
<ul>
{% for genre in genres %}
<li>
<a href="{% url 'book:genre' genre.id %}">{{ genre }}</a>
</li>
{% empty %}
<li>No Genres available.</li>
{% endfor %}
</ul>
Second, you have the tags wrapped incorrectly. See my version.