【问题标题】:Django doesn't store password field in User modelDjango 不在用户模型中存储密码字段
【发布时间】:2019-01-01 14:49:17
【问题描述】:

我使用 Django 的内置注册表单创建了一个注册页面。下面是我的代码

forms.py

from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User


class SignUpForm(UserCreationForm):
    email = forms.EmailField(max_length=254, help_text='Please provide a valid email address.')
    class Meta:
        model = User
        fields = ('username', 'email', 'password1', 'password2')

    def clean(self):
        cleaned_data = super(SignUpForm, self).clean()
        username = cleaned_data.get("username")
        email = cleaned_data.get("email")


        check_email = User.objects.filter(email=email)
        if check_email:
            raise forms.ValidationError(
                "You are already registered!")
            return cleaned_data

        check_username = User.objects.filter(username=username)
        if check_username:
            raise forms.ValidationError(
                "A user with that username already exists")
            return cleaned_data

在我的 views.py 中,这是我为注册进行身份验证的方式

views.py

@csrf_exempt
def signup_users(request):
    if request.method == 'POST':
        form = SignUpForm(request.POST)
        if form.is_valid():
            form.save()
            username = form.cleaned_data.get('username')
            raw_password = form.cleaned_data.get('password1')
            user = authenticate(username=username, password=raw_password)
            print("signup authencticate", user)
            login(request, user)
            return redirect('/')
    else:
        form = SignUpForm()
    return render(request, 'signup.html', {'form': form})

这是我处理用户登录的代码

@csrf_exempt
def login_view(request):
    print(request.user.is_authenticated())
    if request.POST:
        email = request.POST.get('username')
        password = request.POST.get('password')
        user = authenticate(email=email, password=password)
        if user is not None:
            if user.is_active:
                login(request, user)
                return HttpResponseRedirect('/')
        else:
            return render(request, "login.html")   

    else:
        return render(request, "login.html")

当我注册时,一切似乎都很好,但是当我尝试登录时,它就是不允许我登录。

所以当我检查django admin时,我发现了这个

Username: tech1
Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.
Password:
Invalid password format or unknown hashing algorithm.
Raw passwords are not stored, so there is no way to see this user's password, but you can change the password using this form.

我不太明白为什么在注册时没有存储用户密码?

我搜索了它,我从这个答案using User.objects.get_or_create() gives invalid password format in django? 中发现 django 在存储之前加密了密码,我应该使用类似

user, created = User.objects.get_or_create(username="testuser2")
user.set_password('123')

但我不太确定将其放在代码中的哪个位置,或者这有什么帮助?这是怎么回事?

【问题讨论】:

  • 您是否更改了 settings.py 中的 AUTH_USER_MODEL 以指向您的新用户模型?
  • @Taylor 嗯不!我该怎么做?
  • 这解决了您的问题吗?

标签: python django authentication


【解决方案1】:

以下是我如何设置自定义用户模型的基础知识:

在 Settings.py 中添加:

AUTH_USER_MODEL = "accounts.User"

帐户可以是您存储用户模型的任何位置。

用户模型:

from django.contrib.auth.models import (
    AbstractBaseUser,
    BaseUserManager,
    PermissionsMixin
)
from django.conf import settings
from django.db import models
from django.utils import timezone
import binascii
import os



class UserManager(BaseUserManager):
    def create_user(self, email, first_name, last_name, password):
        """
        Creates and saves a User with the given email, date of
        birth and password.
        """
        if not email:
            raise ValueError('Users must have an email address')


        user = self.model.objects.create(
            email=self.normalize_email(email),
            first_name = first_name,
            last_name = last_name,
        )

        user.set_password(password)
        user.save()
        return user

    def create_superuser(self, email, first_name, last_name, password):
        """
        Creates and saves a superuser with the given email, date of
        birth and password.
        """
        user = self.create_user(
            email,
            first_name,
            last_name,
            password
        )
        user.is_superuser = True
        user.save()
        return user


class User(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(
        verbose_name='email address',
        max_length=255,
        unique=True,
    )
    first_name = models.CharField(max_length=40, null=True, blank=True)
    last_name = models.CharField(max_length=140, null=True, blank=True)
    date_joined = models.DateTimeField(default=timezone.now)
    is_active = models.BooleanField(default=True)
    is_staff = models.BooleanField(default=False)

    objects = UserManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['first_name', 'last_name']


    def get_full_name(self):
        # The user is identified by their email address
        return self.email

    def get_short_name(self):
        # The user is identified by their email address
        return self.first_name

    def __str__(self):              # __unicode__ on Python 2
        return self.first_name

    def has_perm(self, perm, obj=None):
        "Does the user have a specific permission?"
        # Simplest possible answer: Yes, always
        return True

    def has_module_perms(self, app_label):
        "Does the user have permissions to view the app `app_label`?"
        # Simplest possible answer: Yes, always
        return True

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

我不记得了,但我很确定经理必须先来。

注册

class SignUp(generic.CreateView):
    form_class = forms.UserCreateForm
    success_url = "accounts/pre/"
    template_name = "accounts/signup.html"
    def form_valid(self, form):
        valid = super(SignUp, self).form_valid(form)
        email, password = form.cleaned_data.get('email'), form.cleaned_data.get('password1')
        new_user = authenticate(email=email, password=password)
        auth_login(self.request, new_user)
        return valid

Forms.py

class UserCreateForm(UserCreationForm):
    class Meta:
        fields = ("email", "password1", "password2", "first_name", "last_name")
        model = get_user_model()

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields["email"].widget.attrs.update({'class': 'form-control', 'placeholder': 'Email'})
        self.fields["first_name"].widget.attrs.update({'class': 'form-control', 'placeholder': 'First Name'})
        self.fields["last_name"].widget.attrs.update({'class': 'form-control', 'placeholder': 'Last Name'})
        self.fields["password1"].widget.attrs.update({'class': 'form-control', 'placeholder': 'Password'})
        self.fields["password2"].widget.attrs.update({'class': 'form-control', 'placeholder': 'Reenter Password'})

【讨论】:

  • 嘿抱歉,我太忙了。是的。谢谢!
猜你喜欢
  • 2011-02-28
  • 2014-04-25
  • 2011-04-12
  • 1970-01-01
  • 1970-01-01
  • 2019-08-01
  • 2016-02-11
  • 2017-08-26
  • 2013-07-05
相关资源
最近更新 更多