2014-07-12 47 views
0

我有Django的urls.py的正則表達式部分的問題。我想爲每個輸入的用戶顯示一個頁面。 我views.py看起來像:Django的網址正則表達式不工作

def tekent(request): 
    tumentry = Entry.objects.get(id=id) 

    return render_to_response("baslik/tekentry.html", locals(), context_instance=RequestContext(request)) 


def tek(request, slug): 
    basliklar = Baslik.objects.filter(active=True).order_by('-updated') 
    baslik = Baslik.objects.get(slug=slug) 
    entryler = baslik.entry_set.all() 
    form2 = EntryForm(request.POST or None) 

    if form2.is_valid(): 
     entry = form2.save(commit=False) 
     entry.baslik = baslik 
     entry.user = request.user 
     entry.save() 
     return HttpResponseRedirect('/entry/%s'%(entry.id)) 


    return render_to_response("baslik/tek.html", locals(), context_instance=RequestContext(request)) 

我主要urls.py(而不是應用程序的)看起來像這樣:

from baslik import * 
urlpatterns = patterns('', 
url(r'^entry/(?P<Entry.id>)/$', 'tekent', name = "tek_entry"), 
) 

,當我上添加Web瀏覽器的入口,它會引發錯誤像這樣:

DoesNotExist at /baslik/entry4/ 
Baslik matching query does not exist. 
Request Method: GET 
Request URL: http://127.0.0.1:8000/baslik/entry4/ 
Django Version: 1.6.5 
Exception Type: DoesNotExist 
Exception Value:  
Baslik matching query does not exist. 
Exception Location: /Users/malisit/Django/sozluk/lib/python2.7/site-packages/django/db/models/query.py in get, line 310 
Python Executable: /Users/malisit/Django/sozluk/bin/python 

我該怎麼辦才能解決這個問題?謝謝。

+0

'R '^項/(ΔP)/ $''不一個有效的Python正則表達式。 – Unihedron

+0

我應該如何改變它以使其工作? – malisit

回答

1

你有幾個問題:

  1. 你的URL模式是無效的,@maremare解釋如何解決它。
  2. 您撥打的網址與您的模式不符。您的網址是/baslisk/entry4/,但您的模式是entry/
  3. 您的查看方法tekent沒有任何參數,所以即使您要修復您的網址格式,您的視圖方法也不會被調用。
  4. 您正在使用locals()。不要這樣做。

這裏是如何解決這些,從您的urls.py

from baslik.views import tekent 
# other imports 

urlpatterns = patterns('', 
    url(r'^entry/(?P<id>\d+)/$', tekent, name = "tek_entry"), 
) 

views.py

from django.shortcuts import render 
from django.shortcuts import redirect 
from django.shortcuts import get_object_or_404 

def tekent(request, id): 
    tumentry = get_object_or_404(Entry, id=id) 
    return render(request, "baslik/tekentry.html", {'tumentry': tumentry}) 

def tek(request, slug): 
    baslik = get_object_or_404(Baslik, slug=slug) 
    basliklar = Baslik.objects.filter(active=True).order_by('-updated') 
    entryler = baslik.entry_set.all() 
    form2 = EntryForm(request.POST or None) 

    if form2.is_valid(): 
     entry = form2.save(commit=False) 
     entry.baslik = baslik 
     entry.user = request.user 
     entry.save() 

     return redirect('tek_entry', id=entry.id) 

    ctx = {'form2': form2, 'baslikar': baslikar, 'entryler': entryler} 

    return render(request, "baslik/tek.html", ctx) 
+0

現在我明白了。非常感謝。這非常有幫助。 – malisit

1

嘗試 url(r'^entry/(?P<id>\d+)/$', 'tekent', name = "tek_entry"),

你爲什麼不使用基於類的看法? DetailView真的很方便這樣的事情。

+0

非常感謝。這有幫助。 – malisit