是否有一种方法可以将模板URL关键字参数从视图函数定义排除



我的模板中有一个以这种方式路由的URL:

锻炼/模板/calendar.html:

<a href="{% url 'workoutcal:add' year=table.0 month=table.1 day=element.0 %}" class="add">Add workout</a>

锻炼/urls.py:

url(r'^add/(?P<year>[0-9]+)/(?P<month>[0-9]+)/(?P<day>[0-9]+)/$', views.add, name = 'add'), #Adding a workout for the date in question. 

workoutcal/views.py:

def add(request,year,month,day):
    return HttpResponse("This is the add page")

如果我用以下方式替换add()

def add(request):
    return HttpResponse("This is the add page")

我有一个错误:

Traceback (most recent call last):
  File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner
    response = get_response(request)
  File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/core/handlers/base.py", line 187, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File 
"/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/core/handlers/base.py", line 185, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
TypeError: add() got an unexpected keyword argument 'year'

表示views.add有一个意外的关键字参数发送给它。假设我想将这些关键字参数传递给calendar.html中的url,因为它们需要获得正确的URL,但是我不想在我看来使用这些参数。有没有办法从视图函数定义中排除参数,而不会得到此错误?

def add(request,year=None,month=None,day=None):

使您的视图函数这样,因为您需要在urlpattern中传递参数,否则会出错

最新更新