So, this is what's going on:
I am able to get a blog post in my Django 2.1 app by its primary key. However, by demand of the marketing team, I was asked to put a slug on the URL, so instead of /blog/1
, I should get /blog/my-blog-post-title
.
Thus, while still using the pk value to get the blog post, I just need to get the url to work the way I intend to.
URL:
path('<slug:slug>/', blog_views.blog_single, name='blog-single')
In the HTML, I always refer to this page as:
href="{% url 'blog-single' pk=blogPost.id slug=blogPost.get_slug %}"
, so that I get both the pk and the slug, which is gotten by the get_slug()
method declared on the Blog model.
The view is here:
def blog_single(request, pk, slug):
context = {}
context['blogPost'] = blogPost.objects.get(id=pk)
...
return render(request, 'blog/blog-single.html', context)
Still, in any page that refers to blog-single
in the href
, I get the following error:
Reverse for 'blog-single' with keyword arguments '{'pk': 2, 'slug': 'my-blog-post-title'}' not found. 1 pattern(s) tried: ['blog\\/(?P<slug>[-a-zA-Z0-9_]+)\\/$']
I have tried so many different answers I found on the Internet, and read the answer on this post extensively, but I just can't get my head around what's not working: What is a NoReverseMatch error, and how do I fix it?
Any suggestions?
The blog-single
url only expects the slug. Do not include the pk
kwarg when using the url
templatetag.
href="{% url 'blog-single' slug=blogPost.get_slug %}"
Then either change blog_single to:
def blog_single(request, slug):
context = {'blogPost': blogPost.objects.get(slug=slug)}
Or:
def blog_single(request, pk=None, slug=None):
...