缺少位置参数
我正在尝试从一个视图中渲染一个ajax响应,但我遇到了一个错误,提示视图缺少位置参数。
这是我收到的错误信息:
Internal Server Error: /schedules/calendar/2014/10/1/
Traceback (most recent call last):
File "/blahblahblah/django/core/handlers/base.py", line 111, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
TypeError: month_view() missing 2 required positional arguments: 'year' and 'month'
这是我的视图:
def month_view(
request,
year,
month,
template='swingtime/monthly_view.html',
user_id=None,
queryset=None
):
'''
Render a tradional calendar grid view with temporal navigation variables.
Context parameters:
today
the current datetime.datetime value
calendar
a list of rows containing (day, items) cells, where day is the day of
the month integer and items is a (potentially empty) list of occurrence
for the day
this_month
a datetime.datetime representing the first day of the month
next_month
this_month + 1 month
last_month
this_month - 1 month
'''
year, month = int(year), int(month)
cal = calendar.monthcalendar(year, month)
dtstart = datetime(year, month, 1)
last_day = max(cal[-1])
dtend = datetime(year, month, last_day)
# TODO Whether to include those occurrences that started in the previous
# month but end in this month?
if user_id:
profile = get_object_or_404(UserProfile, pk=user_id)
params['items'] = profile.occurrence_set
queryset = queryset._clone() if queryset else Occurrence.objects.select_related()
occurrences = queryset.filter(start_time__year=year, start_time__month=month)
这是我的urls.py文件:
from django.conf.urls import patterns, url
from .views import (
CreateSessionView, CreateListingsView, SessionsListView,
month_view, day_view, today_view
)
urlpatterns = patterns('',
url(r'^create-session/$',
CreateSessionView.as_view(), name="create_session"),
url(r'^create-listings/(?P<session>\d+)/$', CreateListingsView.as_view(),
name = 'create_listings'),
url(r'^my-sessions/$', SessionsListView.as_view(), name="session_list"),
url(
r'^(?:calendar/)?$',
today_view,
name='today'
),
url(
r'^calendar/(\d{4})/(0?[1-9]|1[012])/(?P<user_id>\d+)/$',
month_view,
name='monthly-view'
),
url(
r'^calendar/(\d{4})/(0?[1-9]|1[012])/([0-3]?\d)/(?P<user_id>\d+)/$',
day_view,
name='daily-view'
),
)
你可以看到传递的URL是/schedules/calendar/2014/10/1,这里包含了年份和月份的参数(分别是2014和10),还有用户ID参数(1)。为什么Python/Django会说我缺少参数呢?
1 个回答
1
因为你使用的是位置参数,所以 Django 的网址配置(urls)期望命名组的模式和你传给视图的参数名字是一样的。
所以,你需要把
calendar/(\d{4})/(0?[1-9]|1[012])/(?P<user_id>\d+)/
改成
calendar/(?P<year>\d{4})/(?P<month>0?[1-9]|1[012])/(?P<user_id>\d+)/
在你的 urls.py
文件里。