有没有办法从视图函数定义中排除模板url关键字参数?

时间:2017-09-15 10:22:46

标签: python django

我的模板中有一个网址以这种方式发送:

workoutcal /模板/ calendar.html:

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

workoutcal / 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发送了一个意外的关键字参数。让我们说我想将这些关键字参数传递给url中的calendar.html,因为他们需要获取正确的网址,但我不想在我看来使用这些参数。有没有办法从视图函数定义中排除参数而不会出现此错误?

1 个答案:

答案 0 :(得分:2)

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

使你的视图函数像这样,因为你需要在urlpatterns中传递参数,否则它会出错