2013-03-21 127 views
0

我在Django 1.4.3中使用Windows Vista上的Python 2.7進行編程,從而使網站提供產品。所以我有我的/productos子頁面中列出的各種產品。現在我正在嘗試顯示頁面/producto/#,該頁面顯示列出產品的頁面。這裏是我的urls.py,它就像我的網頁索引:匹配查詢不存在Python Django

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

urlpatterns = patterns('demo.apps.home.views', 
     url(r'^$','index_view', name = 'vista_principal'), 
     url(r'^about/$','about_view', name = 'vista_about'), 
     url(r'^productos/$','productos_view', name = 'vista_productos'), 
     url(r'^producto/(?P<id_prod>.*)/$', 'singleProduct_view', 
      name = 'vista_single_producto'), 
     url(r'^contacto/$','contacto_view', name = 'vista_contacto'), 
     url(r'^login/$', 'login_view', name = 'vista_login'), 
     url(r'^logout/$', 'logout_view', name = 'vista_logout'), 
) 

我也有我的views.py一個singleProduct_view功能檢索該產品並將其輸送到我的網站。

def singleProduct_view(request, id_prod): 
     prod = producto.objects.get(id = id_prod) 
     ctx = {'producto':prod} 
     return render_to_reponse('home/SingleProducto.html', ctx, 
            context_instance = RequestContext(request)) 

然而,當我鍵入/producto/2', it gave me PRODUCTO匹配查詢不exist`錯誤。什麼似乎是問題?

+0

嘗試@ Necrolyte2答案 – catherine 2013-03-21 03:36:38

+0

你肯定有產品ID號爲2的數據庫的實體? – catherine 2013-03-21 13:01:39

+0

原來,我有'render_to_reponse'而不是'render_to_response'。在'迴應'中排除's'。感謝大家的幫助。 – Dombey 2013-03-21 23:05:55

回答

0

我建議改變你的網址爲PRODUCTO頁面如下

url(r'^producto/(?P<id_prod>\d+)/$', 'singleProduct_view', 
     name = 'vista_single_producto') 

很可能是你的正則表達式。*是相匹配的字符串,所以你singleProduct_view內部的id_prod竟是一個字符串不是一個數字

**編輯**

那麼你的觀點裏,你需要你的id_prod轉換爲整數

def singleProduct_view(request, id_prod): 
     prod = producto.objects.get(id = int(id_prod)) 
     ctx = {'producto':prod} 
     return render_to_reponse('home/SingleProducto.html', ctx, 
            context_instance = RequestContext(request)) 

您也可以使用get_object_or_404來確保您的對象也存在於數據庫中。 這將改變你的觀點如此

from django.shortcuts import render, get_object_or_404 

def singleProduct_view(request, id_prod): 
     prod = get_object_or_404(producto, id = int(id_prod)) 
     ctx = {'producto':prod} 
     return render_to_reponse('home/SingleProducto.html', ctx, 
            context_instance = RequestContext(request)) 
+0

謝謝,但仍然無法正常工作。 :( – Dombey 2013-03-21 04:44:39

+0

查看更新的答案爲dusual正確的關於字符串/整數問題由於某種原因,我認爲django奇蹟般地轉換,如果正則表達式只匹配一個數字 你仍然想要使用我的正則表達式,而不是。*作爲將匹配任何他們輸入的不只是數字 – Necrolyte2 2013-03-21 12:38:53

+0

是的,正如我已經提到@ Necrolyte2已經提出更好的方法將是使用\ d +和數字,但即使是這樣的實施信息給用戶,而不是更好地仍然可以使用slu gs – dusual 2013-03-21 16:43:52

0

那麼問題很可能是您正在使用的提議可能不會幫助你擺脫錯誤的Unicode字符串但更改URL查詢的Integerfield的事實。因爲你仍然會以字符串的形式獲取參數。

然而,你應該轉換參數id_prod爲int,並且確保你有與ID = 2