Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Adding dynamic url in a reverse function in django

I’m building a blog app, and when posting a comment, and a reply to a comment, the page redirects to the top of the post page, I want it to redirect into the comment\reply that was posted, or scroll into it if you will.

for example, when posting, I want it to go to http://127.0.0.1:8000/post/first#comment-12
to implement something like this:

return HttpResponseRedirect(reverse(f'post_page#comment-{str(comment.id)}', kwargs={ 'slug': slug }))

views.py

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

if request.POST:
    comment_form = CommentForm(request.POST)
    if comment_form.is_valid:
        if request.POST.get('parent'):
            parent_id = request.POST.get('parent')
            parent = Comments.objects.get(id=parent_id)
            if parent:
                comment_reply = comment_form.save(commit=False)
                comment_reply.parent = parent
                comment_reply.post = post
                comment_reply.save()
        else:
            comment = comment_form.save(commit=False)
            post_id = request.POST.get('post_id')
            post = Post.objects.get(id=post_id)
            comment.post = post
            comment.save()
        return HttpResponseRedirect(reverse('post_page', kwargs={ 'slug': slug }))

urls.py

urlpatterns = [
    path('', views.index, name='index'),
    path('post/<slug:slug>', views.post_page, name='post_page')
]

>Solution :

You add the fragment manually at the end of the path, like:

return HttpResponseRedirect(f"{reverse('post_page', kwargs={ 'slug': slug })}#comment-{comment.id}")

I think the redirect(…) [Django-doc] and reverse(…) functions [Django-doc] could have benefited from an optional _anchor parameter that would append the anchor (and also URL encode it).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading