Django用户变成匿名用户

2024-10-02 02:30:28 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我有以下用户模型

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

我在中定义了我的模型设置.py在

^{pr2}$

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

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

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

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语句完美地打印了用户名,如下所示:

[DEBUG] Successfully authenticated user adam

然而

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

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语句将打印出:

[DEBUG] request user is: AnonymousUser

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

谢谢你的帮助…谢谢。在


Tags: thenamegetreturnifrequestpageusername
1条回答
网友
1楼 · 发布于 2024-10-02 02:30:28

原来这个问题很微妙。Django无法获取我的用户,因为我的get-unu-user方法在auth后端出错。在

return User.objects.get(username=user_id)

应该是

^{pr2}$

因为“userID”字段是主键。在

相关问题 更多 >

    热门问题