Django urls正则表达式不起作用

时间:2014-07-12 09:40:12

标签: python regex django django-urls

我对Django的urls.py的正则表达式部分有疑问。我想为每个输入的用户显示一个页面。 我的views.py看起来像:

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"),
)

当我在网络浏览器上添加条目时,会引发如下错误:

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

我应该怎么做才能解决这个问题?感谢。

2 个答案:

答案 0 :(得分:1)

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

为什么不使用基于类的视图? DetailView对于这些事情非常方便。

答案 1 :(得分:1)

你有一些问题:

  1. 您的网址格式无效,@ maremare解释了如何修复它。
  2. 您呼叫的网址与您的模式不匹配。您的网址为/baslisk/entry4/,但您的模式为entry/
  3. 您的查看方法tekent不会带任何参数,因此即使您要修复网址格式,也不会调用您的查看方法。
  4. 您正在使用locals()。不要这样做。
  5. 以下是从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)