簡體   English   中英

Django不在用戶模型中存儲密碼字段

[英]Django doesn't store password field in User model

我使用Django的內置注冊表單創建了注冊頁面,這是下面的代碼

表格

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.

我不太了解為什么在注冊時未存儲用戶密碼?

我進行了搜索,並使用User.objects.get_or_create()從此答案中找到了在django中提供無效密碼格式的信息? django在存儲之前對密碼進行了加密,我應該使用類似

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

但是我不確定在代碼中的什么地方或這有什么幫助?發生了什么?

以下是我如何設置自定義用戶模型的基礎知識:

在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'})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM