django URL映射?

时间:2011-11-02 15:11:44

标签: django django-urls

新手到django和python。尝试获取并运行一些示例日历代码,但是URL映射存在问题。当我尝试运行管理页面(或任何页面)时,我得到:

ViewDoesNotExist at /

Tried main in module cal. Error was: 'module' object has no attribute 'main'

Request Method:     GET
Request URL:    http://127.0.0.1:8000/
Django Version:     1.3.1
Exception Type:     ViewDoesNotExist

这是我的网址模式:

(r"^(\d+)/$", "main"),
(r"", "main"),
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
url(r'^admin/', include(admin.site.urls)),

我很困惑,因为在我看来,在view.py中确实存在函数“main”,如下所示。非常感谢任何帮助:

import time
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import get_object_or_404, render_to_response

from dbe.cal.models import *

mnames = "January February March April May June July August September October November December"
mnames = mnames.split()


@login_required
def main(request, year=None):
"""Main listing, years and months; three years per page."""
# prev / next years
if year: year = int(year)
else:    year = time.localtime()[0]

nowy, nowm = time.localtime()[:2]
lst = []

# create a list of months for each year, indicating ones that contain entries and current
for y in [year, year+1, year+2]:
    mlst = []
    for n, month in enumerate(mnames):
        entry = current = False   # are there entry(s) for this month; current month?
        entries = Entry.objects.filter(date__year=y, date__month=n+1)

        if entries:
            entry = True
        if y == nowy and n+1 == nowm:
            current = True
        mlst.append(dict(n=n+1, name=month, entry=entry, current=current))
    lst.append((y, mlst))

return render_to_response("cal/main.html", dict(years=lst, user=request.user, year=year,
                                               reminders=reminders(request)))

2 个答案:

答案 0 :(得分:3)

错误消息告诉您main模块中不存在cal函数 - 这是正确的,它存在于cal.views模块中。

如果您将网址格式更改为以下内容,则应该有效:

(r"^(\d+)/$", "cal.views.main"),
# (r"", "cal.views.main"),

我已经注释掉了上面的r""网址,因为它是一个捕获所有网址。它显示在登录网址的模式上方,因此您的main视图正在处理日志网址/accounts/login/main视图使用login_required装饰器,导致重定向循环。

答案 1 :(得分:1)

Alasdair的回答是正确的。 我只想添加一个奖励:https://docs.djangoproject.com/en/1.3/intro/tutorial03/#simplifying-the-urlconfs

为了更方便,您可以这样声明:):

urlpatterns = patterns('cal.views',
                       (r'^(\d+)/$', 'main'),
                       (r'', 'main'),
)