Redirect to index page after submiting form in django


Question

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,

  1. first my url looks like >> 127.0.0.1:8000/product/
  2. Then once I hit the add button url changes to 127.0.0.1:8000/product/add_product/ , no problem there, but
  3. when i try to add data again my url goes to 127.0.0.1:8000/product/add_product/add_product and i get a Page not found error

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) ?

1
3
10/1/2012 10:37:24 AM

Accepted Answer

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

7
10/1/2012 10:45:05 AM

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.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon