如何在 Django 中以编程方式验证用户身份?

发布于 2024-12-11 17:47:36 字数 56 浏览 0 评论 0原文

如何在 Django 中以编程方式登录用户?我有用户的用户名和密码。有没有一种方法可以让我登录他?

How can I log-in the user programmatically in Django? I have the username and password of the User. Is there a method that let's me log him in?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

慕巷 2024-12-18 17:47:36

除了“以编程方式”之外,没有其他方法。当然,这是 记录的

from django.contrib.auth import authenticate, login

user = authenticate(username=username, password=password)
if user is not None:
    login(request, user)

There is no other way than "programmatically". Of course, this is documented.

from django.contrib.auth import authenticate, login

user = authenticate(username=username, password=password)
if user is not None:
    login(request, user)
寻梦旅人 2024-12-18 17:47:36

以编程方式登录用户时请务必小心,您可能会收到错误“用户没有属性“后端”。如果以前没有发生过这种情况,您也必须设置后端。 使用此项目和一些示例代码:

def splash_register(request):
  if request.session.get('beta'):

    if request.method=='POST':
        userform=MyUserCreationForm(request.POST)
        if userform.is_valid():
            #username of <30 char is required by Django User model.  I'm storing username as a hash of user email 

            user=userform.save(commit=False)
            user.username=hash(user.email)
            user.backend='django.contrib.auth.backends.ModelBackend'
            user.save()


            username=user.username
            password=str(userform.cleaned_data['password'])
            auth.login(request, user)
            request.session['first_visit']=True
            return HttpResponseRedirect("/")
        else:
            userform=MyUserCreationForm(request.POST)
            return render_to_response("website/splash_register.html", {'userform':userform}, context_instance=RequestContext(request))
    return render_to_response("website/splash_register.html", context_instance=RequestContext(request))     
else:
    return HttpResponseRedirect('/splash/')

Alsways be careful when programmatically logging users in, you might get the error ´user has no attribute "backend". You have to set the backend too if that has no happened previously. Project that uses this and some sample code:

def splash_register(request):
  if request.session.get('beta'):

    if request.method=='POST':
        userform=MyUserCreationForm(request.POST)
        if userform.is_valid():
            #username of <30 char is required by Django User model.  I'm storing username as a hash of user email 

            user=userform.save(commit=False)
            user.username=hash(user.email)
            user.backend='django.contrib.auth.backends.ModelBackend'
            user.save()


            username=user.username
            password=str(userform.cleaned_data['password'])
            auth.login(request, user)
            request.session['first_visit']=True
            return HttpResponseRedirect("/")
        else:
            userform=MyUserCreationForm(request.POST)
            return render_to_response("website/splash_register.html", {'userform':userform}, context_instance=RequestContext(request))
    return render_to_response("website/splash_register.html", context_instance=RequestContext(request))     
else:
    return HttpResponseRedirect('/splash/')
同展鸳鸯锦 2024-12-18 17:47:36

接受的答案肯定有效,但是,我更喜欢使用内置身份验证表单的 Django,例如 django.contrib.auth.forms.AuthenticationForm

下面是一个片段,显示了重要部分

form = AuthenticationForm(request, data=request.POST)
if form.is_valid():
    try:
        form.clean()
    except ValidationError:
        # handle error

    login(request, form.get_user())

这种方法的主要区别是 AuthenticationForm.clean 方法为您调用 authentication 函数并为您检查 User.is_active

The accepted answer definitely works but, I prefer to use the Django built in auth forms, like django.contrib.auth.forms.AuthenticationForm

Here is a snippet that shows the important part

form = AuthenticationForm(request, data=request.POST)
if form.is_valid():
    try:
        form.clean()
    except ValidationError:
        # handle error

    login(request, form.get_user())

The major difference in this approach is that AuthenticationForm.clean method calls authentication function for you and checks User.is_active for you as well.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文