Django2.0; still cannot get how redirect works
Django2.0; still cannot get how redirect works
I'm new to Django and I still don't get how redirect works.
For now, I use this way to redirect.
return HttpResponseRedirect(reverse_lazy('main:index'))
and this way works.
And now I'm creating another page, and what I want to do is to redirect to the same page after I submit the form data.
view.py is like this
def add_comment(request, pk):
entry = Entry.objects.get(id=pk)
if request.method != 'POST':
form = CommentForm()
else:
form = CommentForm(request.POST)
if form.is_valid():
new_comment = form.save(commit=False)
new_comment.user = request.user
new_comment.save()
return redirect('add_comment', pk=entry.id)
return render(request, 'main/add_comment.html', {'form': form, 'entry': entry, 'comments': comments})
urls.py is like this
path('add_comment/<int:pk>', views.add_comment, name='add_comment'),
I can enter this page, but after I submit the form, this error happens.
NoReverseMatch at /add_comment/5
Reverse for 'add_comment' not found. 'add_comment' is not a valid view function or pattern name.
Request URL:
http://127.0.0.1:8000/add_comment/5
even though I can enter this url page, I cannot redirect to the same page.
How am I wrong with this? Also what is the recommended way to redirect to a page?
new_comment.save()
/
/google.com
oops, sorry I deleted the line when I post code here.
– bababa
Jun 30 at 1:28
1 Answer
1
You probably need to change this:
return redirect('add_comment', pk=entry.id)
to this:
return redirect('main:add_comment', pk=entry.id))
Assuming that all your URLs are in the same namespace. If your index
url is defined in the same list as your add_comment
URL then they will be sharing the main
namespace.
index
add_comment
main
This works. Thanks a lot.
– bababa
Jun 30 at 7:00
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Side note are you sure that the model is being filled out correctly? After you add more information to the model you will need to call
new_comment.save()
. If you are not filling out the model correctly it may not be able to navigate to it at that point. Does the redirect work when you navigate to a page that you are sure does work, i.e./
or/google.com
?– tmcnicol
Jun 30 at 1:24