I am trying to redirect the user to the previous page once a form is submitted.
- User starts on Venue_id page (http..../show_venue/23/) and clicks on product id
- User is directed to Product_id page (http..../show_product.../1/) and find a form
- User completes form and submit on Product_id page
- user redirect to Venue_id page upon form submission (from http..../show_venue/23/)
http..../show_venue/23/ -> http..../show_product.../1/ -> http..../show_venue/23/
I found a good source of inspiration on the forum, particularly on this page (How to redirect to previous page in Django after POST request)
(I also found some posts using the history of the browser. But decided to stick to this method, as it seems using browser history doesn't always work)
I used next
as suggested in the code in the above post. But there is something I don't understand which is probably why I get this wrong.
Here is the different codes in views I tried for next
:
next = request.POST.get('next','/')
=> this sends me to '/', which is not what i want. However it seemed to work for the person who posted the original question even though they were trying to NOT be redirect to '/';next = request.POST.get('next','')
=> sends me to my product_id page url, but the page is empty- next = request.POST.get('next') => this one was suggested in other posts, but I get
Field 'id' expected a number but got 'None'
.
I might be completely wrong, but I feel the key is probably there. How to do refer to "show_venue/<venue_id>
" into "next = request.POST.get('next','show_venue/<venue_id>')
"?
In terms of code
Views
def show_product_from_venue(request, product_id):
product = Product.objects.get(pk=product_id)
form = ReviewForm()
venue_form = VenueForm()
submitted = False
next = request.POST.get('next')
if request.method == "POST" and 'btnvenue_form' in request.POST:
venue_form = VenueForm(request.POST)
if venue_form.is_valid():
venue_form.save()
return HttpResponseRedirect(next)
else:
venue_form = VenueForm
if 'submitted' in request.GET:
submitted = True
else:
print(form.errors)
return render(request,"main/show_product_from_venue.html", {'form':form, 'submitted':submitted, 'product':product, 'venue_form':venue_form, 'data':data})
Venue_id (template)
<a href="{% url 'show-product-from-venue' product.id %}?next={{ request.path|urlencode }} method="POST">
Product_id(template with form)
<form action="{% url 'show-product-from-venue' product.id%}" method="POST">
{% csrf_token %}
{{ form}}
<input type="submit" name="btnreview_form" name="next" value="{{ request.GET.next }}" class="btn btn-primary custom-btn">
</form>
urls
#VENUE PAGE
path('show_venue/<venue_id>', views.show_venue,name="show-venue"),
#PRODUCT
path('show_product_from_venue/<product_id>', views.show_product_from_venue,name="show-product-from-venue"),