1

I've been practicing Djnago and for that, I was building a blog. While in the process of building it, I was faced with an error, while using the following code:

<a href="{% url 'blog_post' post.slug %}">
    {{ post.title }}
</a>

While studying and doing other courses something like this would work fine. But now, it will raise this exception: NoReverseMatch.

enter image description here

If I use this code though, it will work just fine:

<a href="{{ post.slug }}">
    {{ post.title }}
</a>

While working in different projects the first way would work fine, but this time, it doesn't.

My question is why?

Here is the code in my urls and on my views. Maybe the mistake is here, not somewhere else.

If anyone can explain why this is happening, or where I'm going wrong, it will be greatly appreciated

urls:

from django.urls import path

from . import views

app_name = 'blog'

urlpatterns = [
    path('', views.blog_index, name='blog_index'),
    path('<slug:post_slug>/', views.blog_post, name='blog_post'),
]

views:

from django.shortcuts import render
from .models import Post

# Create your views here.
def blog_index(request):
    posts = Post.objects.order_by('- 
    created').filter(published=True)
    data = {
        'posts': posts
    }
    return render(request, 'blog/post_list.html', data)

def blog_post(request, post_slug):
    post = Post.objects.get(slug=post_slug)
    data = {
        'post': post
    }
    return render(request, 'blog/post_detail.html', data)
4
  • 1
    Please always post the whole error message with full traceback. NoReverseMatch is not sufficient to debug the issue.
    – Selcuk
    Oct 6, 2021 at 5:22
  • @Selcuk At least (hopefully? I didn't test) there's a minimal reproducible example.
    – user202729
    Oct 6, 2021 at 5:24
  • @user202729 No, there is not. We don't know the input (post) that caused the issue for starters. Also an MCVE is not an excuse for missing debugging information (such as the error message).
    – Selcuk
    Oct 6, 2021 at 5:44
  • @Selcuk thank you! I've updated the question with a print of the error message given by Django. I believe it is clearer now.
    – J.Felipe
    Oct 6, 2021 at 14:58

2 Answers 2

4

try this.your problem is that you have a namespace in your urls.py then in your href you should add that namespace('blog').

<a href="{% url 'blog:blog_post' post.slug %}">
    {{ post.title }}
</a>

this

 <a href="{{ post.slug }}">
    {{ post.title }}
</a>

this code above was working because you are located inside the home page and when you add this(href="{{ post.slug }}" in the a tag) it will just call the current url +"/<'slug:post_slug/' and this is a valid url.but this is a very bad option.use the the first option.
to learn about this refer to this https://docs.djangoproject.com/en/3.2/topics/http/urls/#url-namespaces.

3
  • 1
    More specifically, the question was "why?", not "can you give me code?" Oct 6, 2021 at 5:16
  • 1
    @user202729 thanks for your advice.the problem is that my english is not so good.but i have edited again my answer. Oct 6, 2021 at 5:41
  • 1
    It is bad practice to perform such operations in templates
    – kjaw
    Oct 6, 2021 at 6:20
1

In such cases, you should use: https://docs.djangoproject.com/en/3.2/ref/models/instances/#get-absolute-url The less logic in the templates, the better for the application. It is difficult to write tests on logic that is contained in templates.

You should add a method to your model:

from django.urls import reverse

class Post()
    ...
    def get_absolute_url(self):
        return reverse('blog:blog_post', kwargs={'post_slug' : self.slug})

In the reverse function you need to add an application namespace. In your case, it's a blog. https://docs.djangoproject.com/en/3.2/topics/http/urls/#introduction

and then in template use:

{{ post.get_absolute_url }}

From documentation:

The logic here is that if you change the URL structure of your objects, even for something small like correcting a spelling error, you don’t want to have to track down every place that the URL might be created. Specify it once, in get_absolute_url() and have all your other code call that one place.

3
  • 1
    While technically correct, this is not an answer to the question asked. We don't know the reason OP's code fails and reverse will fail similar to {% url %} under the same circumstances.
    – Selcuk
    Oct 6, 2021 at 6:39
  • 1
    I added the information that application namespace should be added. I wrote working code, but I actually forgot that it might not be obvious. @Selcuk
    – kjaw
    Oct 6, 2021 at 8:28
  • 1
    Your answer works well for me. I'm choosing the other answer as the right one for familiarity but, yours seem to be a good choice as well. Still trying to figure out, which one is a better practice. I'll be looking into this one. Thank you!
    – J.Felipe
    Oct 6, 2021 at 15:52

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.