2017-09-22 38 views
0

我对Python和Django非常陌生,正在查看使用Django内置登录系统(django.contrib.auth.login)的代码。如何从django.contrib.auth(Django内置登录系统)获取用户名?

用户登录后,我想根据用户权限将用户重定向到适当的URL。例如,某些用户名拥有管理员权限,而有些则只是普通用户。但是,点击“登录”按钮后,用户总是被重定向到相同的URL。

为了以不同方式重定向用户,我必须检查用户名,并检查用户具有的权限。但是,我找不到任何方法从django.contrib.auth.login中获取用户名。就好像用户名在验证通过后就消失了一样。

有谁知道如何解决这个问题?

谢谢!

+0

你应该告诉你正在使用的代码,并指出其中的用户名“消失”。 –

+0

经过身份验证的用户存储在请求对象中的'用户'属性下。如果您使用基于类的视图,则可以在视图中使用'request.user'或'self.request.user'来检索它。这很好地解释了[在文档中](https://docs.djangoproject.com/en/1.11/topics/auth/default/#authentication-in-web-requests)。 – Antwane

+0

[此问题](https://stackoverflow.com/questions/16824004/django-conditional-login-redirect/16824337#16824337)可能会有所帮助。 – Alasdair

回答

0

好吧,如果你能够登录他,你应该有类似的东西(在此部分代码):

0

登录视图支持“下一个”参数。因此,在您的表单模板,你可以这样添加:

<form method="POST"> 
    {% csrf_token %} 
    <input type="hidden" name="next" value="/go/here/if/successful" /> 
    {{ form }} 
</form> 

要做到这一点的看法,同时尊重下一个参数,并提供根据用户不同的默认值:

from django.contrib.auth.views import LoginView 

class MyLoginView(LoginView): 
    def get_redirect_url(self): 
     next = super(MyLoginView, self).get_redirect_url() 
     if not next: 
      user = self.request.user # see form_valid and auth.login() 
      if user.is_staff: 
       return '/staff/goes/here' 

     return next 
0

在登录模板有的喜欢:

<form action="/login/" method="post"> 
    <input type="text" name="username" placeholder="username"/> 
    <input type="password" name="password" placeholder="password"/> 
</form> 

而且在像django docs后台说:

from django.contrib.auth import authenticate 
user = authenticate(username='john', password='secret') 
if user is not None: 
    # A backend authenticated the credentials 
else: 
    # No backend authenticated the credentials 
0

您可以使用视图和绑定网址下面的代码索引功能

from django.shortcuts import render 

def index(request): 
    if request.user.is_admin and request.user.is_active: 
     return render(request, 'admin-page.html') 
    return render(request, 'user-page.html') 
相关问题