简体   繁体   English

我正在尝试使用 django 登录。 但总是失败。 为什么?

[英]I'm trying to login with django. but always fail. why?

i'm doing my own project.我正在做我自己的项目。 the project is signup, signin in django.该项目正在注册,在 django 中登录。 i make my own model.我自己做 model。 not django model.不是 django model。 i use AbstractBaseUser, and create my own model.我使用 AbstractBaseUser,并创建自己的 model。 this model get name, id, companyname, companycode.此 model 获取名称、ID、公司名称、公司代码。 i succeed signup.我注册成功。 get name, id, companyname, companycode.获取姓名、ID、公司名称、公司代码。 and save mysql.并保存 mysql。 but when i login with this information, always fail.但是当我使用此信息登录时,总是失败。 i think authentication function is error.我认为身份验证 function 是错误的。 but i don't know where is the error.但我不知道错误在哪里。 could you help me?你可以帮帮我吗?

models.py模型.py

class UserManager(BaseUserManager):
    use_in_migrations = True
    def create_user(self, username, userid, company, companycode, password=None):

        if not username:
            raise ValueError(_('Users must have an name!'))

        user = self.model(
            username=username,
            userid = userid,
            company= company,
            companycode = companycode,
        )

        user.save()
        return user

    def create_superuser(self, username, userid, company, companycode, password):
        user = self.create_user(
            username=username,
            userid = userid,
            company = company,
            companycode = companycode,
            password=password,
        )
        user.set_password(password)
        user.is_superuser = True
        user.save()
        return user



class User(AbstractBaseUser, PermissionsMixin):
    username = models.CharField(max_length=10, unique=True, verbose_name="이름")
    userid = models.CharField(max_length=100, unique=True, verbose_name="아이디")
    company = models.CharField(max_length=10, verbose_name="회사")
    companycode = models.CharField(max_length=100, verbose_name="회사코드")
    created_date = models.DateTimeField(auto_now_add=True, verbose_name="생성날짜")
    is_admin = models.BooleanField(default=False)
    #is_active = models.BooleanField(default=True)

    class Meta:
        db_table = 'user'

    objects = UserManager()
    USERNAME_FIELD = 'username'
    REQUIRED_FIELDS = ['userid', 'company', 'companycode']
    def __str__(self):
        return self.username

    def get_full_name(self):
        return self.username

    def get_short_name(self):
        return self.username

    @property
    def is_staff(self):
        "Is the user a member of staff?"
        # Simplest possible answer: All superusers are staff
        return self.is_superuser

    get_full_name.short_description = _('Full name')

backend.py后端.py

from django.contrib.auth.backends import ModelBackend
from django.contrib.auth.models import User
from useraccount.models import User
from django.contrib.auth.hashers import check_password
class UseraccountBackend(ModelBackend):
    def authenticate(self, request, **kwargs):
         username = kwargs['username']
         companycode = kwargs['companycode']

         try:
             useracc = User.objects.get(username=username, companycode=companycode)
             if check_password(companycode, kwargs['companycode']) is True:
                 return useracc.username
             '''
             if useracc.companycode.check_password(code) is True:
                 return useracc.username
                 '''
         except User.DoesNotExist:
             pass

views.py视图.py

def login(request):
    if request.method == 'GET':
        return render(request, 'useraccount/login.html')

    elif request.method == 'POST':
        name = request.POST.get('name',None)
        code = request.POST.get('code',None)

        user = authenticate(username=name, companycode=code)

        if user is not None:
            login(request, user)
            return render(request, 'useraccount/login_success.html')
        else:
            return render(request, 'useraccount/login_fail.html')

def signup(request):
    if request.method == 'GET':
        return render(request, 'useraccount/signup.html')
@csrf_exempt
def signup_sign(request): #일반유저 회원가입
    if request.method == 'POST':
        username = request.POST['name']
        userid = request.POST['id']
        company = request.POST['company']
        code = request.POST['code']
        account = User.objects.create_user(
            username=username,
            userid = userid,
            company = company,
            companycode = code,
        )
        #login(request, account)
        account.save()
    return render(request, 'useraccount/success.html')

在此处输入图像描述

在此处输入图像描述

I think your first problem is here:我认为您的第一个问题在这里:

companycode = kwargs['companycode']

[snip]

if check_password(companycode, kwargs['companycode']) is True:

check_password() takes two arguments -- a plaintext password and an encoded password. check_password()需要两个 arguments——一个明文密码和一个编码密码。 You are passing the same value for both, so I would not expect that to return True .您为两者传递了相同的值,所以我不希望它返回True

(Bonus tip, you don't want to return useracc.username , which would be a string. You want to return useracc which should return a user object.) (额外提示,你不想返回useracc.username ,这将是一个字符串。你想返回useracc ,它应该返回一个用户 object。)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我正在尝试在 django 中制作 model。 但错误。 为什么? - I'm trying to make model in django. but error. why? 我正在尝试将 celery 应用于 django 中基于 Class 的视图(apis)。 我怎样才能做到这一点? - I'm trying to apply celery to Class based view(apis) in django. How can I do this? 请我是 python 的新手,我正在尝试使用 Django 做一个食谱应用程序。 我遇到了一个错误,即“UnboundLocalError:局部变量形式 - Please I'm new to python and I'm trying to do a recipe app using Django. I encountered an error which is "UnboundLocalError: local variable form 我正在尝试使用python在ubuntu上安装django = 1.9,并且在管理员登录时遇到以下错误 - I'm trying to install django=1.9 on ubuntu using python and I'm getting the following errors for admin login 将主键与 Django 中的 url 匹配。 当我尝试输入 url: (localhost:8000/detail/S1111111A/) 它总是显示不匹配错误 - Matching Primary key with url in Django. When I am trying to enter the url: (localhost:8000/detail/S1111111A/) it always shows a mismatch error Django的。 登录后重定向用户 - Django. Redirecting user after login Django的。 TestCase login_required - Django. TestCase login_required 我正在使用 django 创建一个日历应用程序。 日历必须是垂直的 - I`m creating a calendar-app using django. Calendar must be vertical Django的。 如何将下一个变量传递给auth_views.login - Django. How do I pass the next variable to auth_views.login 当我尝试从登录表单后面抓取文本时,为什么会得到 []? - Why do I get [] when I'm trying to scrape text from behind a login form?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM