2012-10-01 53 views
2

除了在添加產品數據後重定向回索引頁之外,所有工作都正常,當前我的數據獲取保存後它被重定向到127.0.0.1:8000/product/add_product/ add_product在django提交表單後重定向到索引頁

目前在我的索引頁(add_product.html)負載,我有一個從數據庫中呈現的數據表,

  1. 第一我的網址看起來像>>127.0.0.1:8000/product/
  2. 然後,一旦我打的添加按鈕網址更改爲127.0.0.1:8000/product/add_product/,有沒有問題,但
  3. 當我嘗試添加數據再次我的網址去127.0.0.1:8000/產品/ add_product/add_product,我得到一個找不到網頁錯誤

我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}) 

我的urls.py

from django.conf.urls.defaults import patterns, include, url 

urlpatterns = patterns('product.views', 
    url(r'^$', 'index'),      
    url(r'^add_product/$', 'add_product'), 
) 

如何獲取指向我的索引頁(add_product.html)的URL?

回答

6

127.0.0.1:8000/product/add_product/回報這個

from django.http import HttpResponseRedirect 

def add_product(request) 
    ........................... 
    ........................... 
    return HttpResponseRedirect('/') 

它會重定向到索引頁面視圖。 也可以嘗試給URL名稱,這樣就可以使用反向,而不是「/」

感謝

+0

是否奏效? –

+0

它的工作,我不得不添加「返回HttpResponseRedirect('/產品')」,因爲它的產品模板文件夾內,謝謝很多@Paritosh辛格 – shabeer90

+1

好吧嘗試使用URL反向命名爲URL,PLZ不硬編碼網址,會影響代碼的可維護性。 –

3

您可能已設置窗體的action錯誤在你的模板。

取而代之的是相對URL,

<form method="post" action="add_product"> 

行動應該有絕對的網址:

<form method="post" action="/product/add_product"> 

作爲改進,可以使用url模板標籤,讓你不需要在模板中對網址進行硬編碼。

{% load url from future %} 
<form method="post" action="{% url 'add_product' %}"> 

上面的代碼片段使用新的url語法,通過加載新的url標記。

+0

謝謝你,同時保持當前網址render_to_response在問題中,只根據你所說的改變,也可以完美地工作 – shabeer90

+3

你只能在堆棧溢出中選擇一個答案,但在您的代碼中,您可以同時使用這兩個答案!成功更新後重定向是一個好主意 - 它可以防止用戶多次意外刷新和提交相同的數據。使用'url'標籤也是很好的做法。 – Alasdair