首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Django用户变成匿名用户

Django用户变成匿名用户
EN

Stack Overflow用户
提问于 2018-03-28 00:41:22
回答 1查看 1.2K关注 0票数 0

我正在尝试使用自定义用户模型执行django身份验证。注意:这是一个学校项目,而不是

我有以下用户模型

代码语言:javascript
复制
class User(AbstractBaseUser):
    userID = models.AutoField(primary_key=True)
    username = models.CharField(max_length=20, unique=True)
    password = models.CharField(max_length=24)
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=50)
    USERNAME_FIELD = "username"
    REQUIRED_FIELDS = ["first_name", "last_name"]

    def get_full_name(self):
        return self.first_name + " " + self.last_name

    def get_short_name(self):
        return self.username

    class Meta:
        db_table = "User"
        app_label = "funbids"
        managed = False

我用settings.py定义了我的模型

代码语言:javascript
复制
AUTH_USER_MODEL = 'funbids.User'

我还使用了一个自定义的auth后端。注意:这只是一个使用明文密码的测试(我知道这在任何生产环境中都是一个糟糕的想法)。我使用自定义身份验证后端,因为此应用程序的一个要求是使用现有数据库的原始SQL查询进行身份验证。

代码语言:javascript
复制
class AuthBackend(object):
    """
    Authenticate a user in funbids
    """

    def authenticate(self, request, username=None, password=None):
        # Test credentials
        cursor = connections["funbids"].cursor()
        cursor.execute("SELECT 1 FROM User WHERE username=%s AND password=%s", [username, password])
        if cursor.fetchone():
            # Have to grab the model, then authenticate
            user = User.objects.get(username=username)
            return user
        else:
            return None

    def get_user(self, user_id):
        try:
            return User.objects.get(username=user_id)
        except User.DoesNotExist:
            return None

在我的登录视图中,一切似乎都正常。

代码语言:javascript
复制
def login_user(request, login_failed=False):
    # Redirect the user to the index if they're already authenticated and arrive at the login page
    if request.user.is_authenticated:
        return redirect("funbids:index")

    # Get the username and password from POST data
    username = request.POST.get("username", "")
    password = request.POST.get("password", "")
    next = request.POST.get("next", "")

    # Attempt to authenticate the user if both a username and password are present
    if username and password:
        log.debug("User %s requesting login" % username)

    # Test credentials
    user = authenticate(request, username=username, password=password)
    if user is not None:
        login(request, user)
        log.debug("authenticated user is: %s" % request.user)
        request.session.set_expiry(46800)
    else:
        login_failed = True

    if request.user.is_authenticated:
        # Authentication succeeded. Send the user to the original page they requested
        # using the the "next" POST data or the index.
        log.debug("Successfully authenticated user %s" % request.user)
        if next:
            return redirect(next)
        else:
            return redirect("funbids:index")
    else:
        # Failed authenticate, send back to login page
        log.debug("Failed to authenticate user %s" % username)

# No credentials present/user failed auth - just load the page and populate the "next" form input
# in case the user was redirected here from a view they couldn't access unauthenticated.
next = request.GET.get("next", "")
try:
    template = loader.get_template("funbids/login.html")
except TemplateDoesNotExist:
    raise Http404("Page Not Found")
context = {
    "pagetitle": "Welcome to FunBids!",
    "next": next,
    "login_failed": login_failed,
    "template": template,
    "request": request,
}

# Return the rendered page for display.
return render(request, template_name="funbids/page.html", context=context)

debug语句完美地打印用户名,如下所示:

代码语言:javascript
复制
[DEBUG] Successfully authenticated user adam

然而,

一旦我切换到另一个视图,我将不再登录。相反,我是一个匿名用户,例如:

代码语言:javascript
复制
def search(request):
    log.debug("request user is: %s" % request.user)
    try:
        template = loader.get_template("funbids/search.html")
    except TemplateDoesNotExist:
        raise Http404("Page Not Found")
    context = {
        "pagetitle": "Search items for sale",
        "template": template,
        "request": request,
    }

    # Return the rendered page for display.
    return render(request, template_name="funbids/page.html", context=context)

这一次,debug语句打印出来:

代码语言:javascript
复制
[DEBUG] request user is: AnonymousUser

我在这个问题上做了一些阅读,发现当用户通过身份验证,但没有登录时,就会发生这种情况。但是,我可以成功登录,没有任何问题,所以我不确定发生了什么。

任何help...thanks都会很感激。

EN

回答 1

Stack Overflow用户

发布于 2018-03-28 02:34:08

事实证明,这个问题非常微妙。Django无法获取我的用户,因为我的get_user方法在我的身份验证后端是错误的。

代码语言:javascript
复制
return User.objects.get(username=user_id)

应该是

代码语言:javascript
复制
return User.objects.get(userID=user_id)

因为"userID“字段是主键。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49518285

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档