Everything works correctly apart from redirecting back to the index page after adding the products data, currently after my data gets save it gets redirected to 127.0.0.1:8000/product/add_product/add_product
Currently when my index page(add_product.html) loads, I have a table that renders data from the database,
My views.py
from models import Product,Category
from django.shortcuts import render_to_response,get_object_or_404
from django.http import HttpResponseRedirect
def index(request):
category_list = Category.objects.all()
product_list = Product.objects.all()
return render_to_response('product/add_product.html', {'category_list': category_list, 'product_list':product_list})
def add_product(request):
post = request.POST.copy()
category = Category.objects.get(name=post['category'])
product = post['product']
quantity = post['quantity']
price = post['price']
new_product = Product(category = category, product = product, quantity = quantity, price = price )
new_product.save()
category_list = Category.objects.all()
product_list = Product.objects.all()
return render_to_response('product/add_product.html', {'category_list': category_list, 'product_list':product_list})
My urls.py
from django.conf.urls.defaults import patterns, include, url
urlpatterns = patterns('product.views',
url(r'^$', 'index'),
url(r'^add_product/$', 'add_product'),
)
How do i get the URL pointing back to my index page(add_product.html) ?
You'll also need to have created the redirect page or know the URL that you want to redirect users to. Open your form and then select Settings > Confirmations > Default Confirmations. Under Confirmation Type, you can then choose to redirect users to a page on your website or a specific URL.
Django Redirects: A Super Simple Example Just call redirect() with a URL in your view. It will return a HttpResponseRedirect class, which you then return from your view. Assuming this is the main urls.py of your Django project, the URL /redirect/ now redirects to /redirect-success/ .
In the view of 127.0.0.1:8000/product/add_product/ return this
from django.http import HttpResponseRedirect
def add_product(request)
...........................
...........................
return HttpResponseRedirect('/')
It will redirect to index page. Also try to give url name so that you can use reverse instead of '/'
Thanks
You may have set your form's action
incorrectly in your template.
Instead of a relative url,
<form method="post" action="add_product">
the action should have the absolute url:
<form method="post" action="/product/add_product">
As an improvement, you can use the url
template tag, so that you don't need to hardcode the url in the template.
{% load url from future %}
<form method="post" action="{% url 'add_product' %}">
The snippet above uses the new url syntax, by loading the new url tag.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With