Issue
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
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).
Answered By - willeM_ Van Onsem
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.