如何使用Django的身份验证系统登录现有用户?

时间:2017-02-03 03:01:41

标签: python django

def sign_in(request):
    #we need to handle all the data that was just typed, we'll add a condition for that
    form = NameForm(request.POST)
    if form.is_valid():
        post = form.save()
        post.save()
        username = request.POST.get('username')
        password = request.POST.get('password')
        #auth = authenticate(username=username, password=password)
        # If the username and password are provided try to auth them
        if username and password:
            print username, password
            user = authenticate(username=username, password=password)
            # if it authenticates successfully, check if the user is not an admin, log them in
            if user:
                if not user.is_staff:
                    login(request,user)
                return HttpResponseRedirect('success')
    else:
        form = NameForm()
    return render(request, 'checkin/sign_in_new.html', {'form': form})

编辑:更改了代码以使用后端。添加了user.is_staff但它仍然不会返回任何网页,它只会停留在同一个网页上

models.py

from __future__ import unicode_literals

from django.db import models
from django import forms
from django.forms import ModelForm

# Create your models here.

class Question(models.Model):
    question_text = models.CharField("What is your ID?", max_length=100, null=True)
    #pub_date = models.DateTimeField('date published')

    id_text = models.CharField("", max_length=200, null=True)

    def __str__(self):
        return self.question_text 

forms.py

from django.forms import ModelForm
from .models import Question

#put the form here

class NameForm(ModelForm):
    class Meta:
        model = Question
        fields = ['question_text', 'id_text']

class IdForm(ModelForm):
    class Meta:
        model = Question
        fields = ['id_text']

编辑2 这些是我的模型和表单文件,如果它们不影响我后端中某些参数的命名?

2 个答案:

答案 0 :(得分:1)

我就是这样做的,它有效...但我自动创建用户,所以没有表单输入,但你应该明白这个想法:

            user, created = User.objects.get_or_create(username=user_email, email=user_email)

            if created:
                secret = str(uuid4())
                user.set_password(secret)
                user.save()

            user = User.objects.get(username=user_email)
            user.backend = 'django.contrib.auth.backends.ModelBackend'
            login(request, user)

所以对你来说,你可以使用User.objects.get_or_create ...代替create_user

你显然必须添加auth步骤。

答案 1 :(得分:1)

Django身份验证系统。

我认为您熟悉使用模型保存用户数据 您可以使用身份验证后端来解决此问题,请参阅以下步骤。创建自定义后端。在项目根目录中 后端/ staff_backends.py

from project_app_path.staffs.models import MODEL_NAME
from django.contrib.auth.hashers import check_password
from django.contrib.auth.models import User
class StaffBackend:
    def authenticate(self, username=None, password=None):

        try:
            user = MODEL_NAME.objects.get(username=username)
            if check_password(password, user.password):
                return user
            else:
                return None
        except MODEL_NAME.DoesNotExist:
            return None
    def get_user(self, user_id):
        try:
            return MODEL_NAME.objects.get(pk=user_id)
        except MODEL_NAME.DoesNotExist:
            return None

包含项目设置的后端。

AUTHENTICATION_BACKENDS = [ 

'django.contrib.auth.backends.ModelBackend',
'backends.staff_backends.StaffBackend',

]
在views.py中

from django.contrib.auth import authenticate, login ,logout

def any_view(request):
    rg = request.POST.get
    username = rg('username')
    password = rg('password')
    if username and password:
        print username,password
        user = authenticate(username=username,password=password)
        if user:
            if not user.is_staff:
                login(request,user)
            ### Redirect where you want , you can use this code in to you  signupage also.