错误: TypeError:loadshortlink()为参数“ shortlink”获得了多个值
我的urls.py:
path('s/<str:shortlink>',views.loadshortlink, name="get_longlink")
views.py:
def loadshortlink(shortlink):
print("Translating short link %s" % shortlink)
link = get_longlink(shortlink)
return render(request, 'shortlinks/openlong.html', {
'link': link
})
def get_longlink(shortlink):
print('Short link is %s' % shortlink)
links = Links.objects.filter(shortlink=shortlink)
if len(links)>1 or len(links)==1:
link = links[0].longlink
return link
else:
return 'No matched long links'
当我访问网址时:http://127.0.0.1:8000/s/4nI
我得到了错误:
Internal Server Error: /s/4nI
Traceback (most recent call last):
File "/home/joel/.local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/home/joel/.local/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/joel/.local/lib/python3.6/site-packages/django/core/handlers/base.py", line 124, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
TypeError: loadshortlink() got multiple values for argument 'shortlink'
为什么会这样?
答案 0 :(得分:1)
视图函数的第一个参数应该是请求。您需要将其添加到hrtable
:
loadshortlink
答案 1 :(得分:0)
实际上,它无法处理请求,因为loadshortlink方法缺少请求参数。您的代码应为:
def loadshortlink(request, shortlink):
print("Translating short link %s" % shortlink)
link = get_longlink(shortlink)
return render(request, 'shortlinks/openlong.html', {
'link': link
})
def get_longlink(shortlink):
print('Short link is %s' % shortlink)
links = Links.objects.filter(shortlink=shortlink)
if len(links)>1 or len(links)==1:
link = links[0].longlink
return link
else:
return 'No matched long links'