Search code examples
javascripthtmldjangojinja2

NoReverseMatch at / Reverse for 'story' with keyword arguments '{'id': ''}' not found. 1 pattern(s) tried: ['story/(?P<id>[0-9]+)\\Z']


I'm getting this error: NoReverseMatch at / Reverse for 'story' with keyword arguments '{'id': ''}' not found. 1 pattern(s) tried: ['story/(?P<id>[0-9]+)\\Z']

For this line in my template: .

When I am trying to print it to the screen ({{ subject.list.0.id }}) it prints the id without any problem, but for some reason when I am trying to pass it here <a href="{% url 'story' id=subject.list.0.id %}">, it doesn't work.

the URL: path("story/<int:id>", views.story, name="story"),

the view:

def story(request, id):
story = Story.objects.get(id=id)
last_post = story.posts.all()[::-1][0]
return render(request, "story.html", {
    "posts": story.posts.all(),
    "deadline": last_post.deadline,
})

The page view:

def index(request):
user = User.objects.get(id=request.user.id)
user_genre = user.genres.all()
stories = [{'list': Story.objects.order_by("-likes").all()[0:20], 'popular': 'true'}, 
            {'list': Story.objects.all()[::-1][:20], 'new': 'true'}, ]
for genre in user_genre:
    stories.append({'list': Story.objects.filter(genres=genre)[0:20], "genre": genre})
print(stories)
return render(request, "homepage.html", {
    "genres": Genre.objects.all(),
    "user": User.objects.get(id=request.user.id),
    "stories": stories
})

*The 'subject' in the homepage template is from {% for subject in stories %}.

Edited:

When I try to execute stories=Story.objects.all() and then use it in the template as <a href="{% url 'story' id=subject.id %}">link</a>, it works amazingly. However, my intention is not to use all the posts. Instead, I am attempting to pass stories to the template using the following structure:

stories = [{'list': Story.objects.order_by("-likes").all()[0:20], 'popular': 'true'},
           {'list': Story.objects.all()[::-1][:20], 'new': 'true'}, ]

Now, an issue arises when I attempt to print {{ subject.list.0.id }}. It successfully prints the ID, but I am unable to pass the ID in the following manner: <a href="{% url 'story' id=subject.list.0.id %}">. Unfortunately, this approach does not work.

Here is an example to illustrate the problem:

{{ stories }}<br><br>
{{ subject }}<br><br>
{{ subject.list }}<br><br>
{{ subject.list.0 }}<br><br>
{{ subject.list.0.id }}<br><br>

enter image description here

What can be the problem? What am I missing? I will appreciate any help!


Solution

  • The issue is that you are not checking if {{ subject.list.0 }} exists or not. A simple workaround is to access {{ subject.list.0.id }} only if length of subject.list > 0.

    Try this jinja snippet

    {%for subject in stories%}
        {% if subject.list|length > 0 %}
            <a href="{% url 'story' id=subject.list.0.id %}">link</a>
        {% endif %}
    {% endfor %}