django在视图和模板中使用url参数

时间:2018-07-24 18:49:05

标签: python django

我正在使用Django 2.1+和Python 3.6 +。

在我的urls.py中,我有以下网址:

url('^member/(?P<username>[\w\-]+)/$', views.Member, name='member_data'),

仅此一项即可:

但是从两个视图来看:

def login(request):
    email = request.POST['email']
    password = request.POST['password']
    username = User.objects.get(email=email)
    user = authenticate(request, username=username.username, password=password)
    if user is not None:
        auth_login(request, user)
        # Redirect to a success page.
        return reverse('member_data', {'username': username.username})
    else:
        # Return an 'invalid login' error message.
        return redirect('login_page', {'error': 1})

并从模板开始(注意,这是一个硬代码用户名,试图使模板起作用):

<a href="{% url 'member_data' username='cheng' %}"><i class="ion ion-person"></i>My Service Record</a>

导致参数错误,我无法解决。因此, 这里的任何智慧将不胜感激。是否应该为两个链接读取该信息?

我开始出现的错误是由于尝试登录引起的:

Environment:


Request Method: POST
Request URL: http://127.0.0.1:8000/login_action/

Django Version: 2.1b1
Python Version: 3.6.3
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'mptt',
 'svcrecord']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']



Traceback:

File "/Users/sinistersparrow/venv/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
  34.             response = get_response(request)

File "/Users/sinistersparrow/venv/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
  126.                 response = self.process_exception_by_middleware(e, request)

File "/Users/sinistersparrow/venv/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
  124.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/Users/sinistersparrow/PycharmProjects/ifthqcom/svcrecord/views.py" in login
  36.         return reverse('member_data', {'username': username.username})

File "/Users/sinistersparrow/venv/lib/python3.6/site-packages/django/urls/base.py" in reverse
  30.     resolver = get_resolver(urlconf)

Exception Type: TypeError at /login_action/
Exception Value: unhashable type: 'dict'

这是直接进入页面时的错误:

更新#1 ...

该模板现在可以正常工作了。仍在处理该视图。 谢谢

1 个答案:

答案 0 :(得分:1)

reverse(..) [Django-doc]参数具有签名:

reverse(viewname, urlconf=None, args=None, kwargs=None, current_app=None

现在当然是我们感兴趣的kwargs了。但是这样的通话:

return reverse('member_data', {'username': username.username})

我们实际上将 dictionary 传递给urlconf参数,但这并不需要字典。

不过,我们可以通过将其传递给名为 的参数来传递给kwargs参数,例如:

return reverse('member_data', kwargs={'username': username.username}))

您还需要将其包装在redirect(..) 中,以将浏览器重定向到此URL:

return redirect(reverse('member_data', kwargs={'username': username.username})))

但是Django接受redirect(..)也直接包含一个视图(名称)和参数,例如:

return redirect('member_data', username=username.username)