Django Template changing html attribute based on slug and current request
When I tried to iterate through a list of post titles to create links in a django template the urls never match the requested path (matching the current web page should alter the formatting on the page for that list item). When I try and change things, Django spits out a 404 error which doesn't let me diagnose the problem or it "works" but not as expected.
the relevant url patterns:
path('<slug:post>', views.blog_post, name='entries')
the relevant views function:
def blog_post(request, post):
try:
return render(request, 'blog/post.html', {
'post_title':post,
'post_content':blog_posts[],
'posts':blog_posts.keys
})
except:
raise Http404()
the template:
<ul>
{% for post in posts %}
{% url "blog:entries" "{{post}}" as blog_entry %}
<li><a href="/blog/{{post}}" {% if request.path == blog_entry %} class="active"{% endif %}>
<span class="item">{{post}}</span>
</a></li>
{% endfor %}
</ul>
I suspect the {% url "blog:entries" "{{post}}" as blog_entry %}
in the template is not resolving correctly as when I replace the href with {% blog_entry %}
it causes a 404 error.
I have tried hard coding it in, I have tried different ways of writing the url, I have tried changing the syntax (in case I am doing it incorrectly. I have checked the page source when I have run tests. I have never been able to get the class attribute to be "active" when on the matching page.
urls.py never get the right path because you did some errors. If I understood you correctly you want single blog to be seen in details (to get single blog object).
urls.py
path('blog/' all_blogs, name='all_blogs'), # all blogs
path('blog/<str:slug>', views.single_blog, name='single_blog'), # one blog
views.py
def all_blogs(request):
blogs = Blogs.objects.all()
return render(request, tmpl_name, {'blogs':blogs})
def single_blog(request, slug):
try:
blog = Blog.obejcts.get(slug=slug)
return render(request, tmpl_name, {"blog":blog})
except Blog.DoesNotExist:
# You can return error message or 404 page what ever you like.