且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在Django中提交表单后重定向到索引页面

更新时间:2022-10-16 23:12:30

127.0.0.1:8000/product/add_product/的视图中返回此

从django.http中的
 导入HttpResponseRedirectdef add_product(请求)........................................................................返回HttpResponseRedirect('/') 

它将重定向到索引页面.另外,尝试提供 URL名称,以便您可以使用反向代替'/'

谢谢

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

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