【问题标题】:I got this error NOT NULL constraint failed: accounts_user.password我收到此错误 NOT NULL 约束失败:accounts_user.password
【发布时间】:2020-06-07 07:26:20
【问题描述】:

问题是当我尝试注册时出现此错误:

django.db.utils.IntegrityError: NOT NULL 约束失败:accounts_user.password

我尝试迁移并执行了所有推荐的操作,例如迁移,但没有成功。

这是我的文件

views.py

from django.shortcuts import render
from django.urls import reverse
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse,HttpResponseRedirect
from django.contrib.auth import authenticate,login,logout
from django.views.generic import FormView,TemplateView,ListView
from django.conf import settings
from .forms import RegisterForm
from .models import User
# Create your views here.




#user-login view
def register(request):
    registred=False
    if request.method=="POST":

        user_register=RegisterForm(data=request.POST)
        if user_register.is_valid():
            username=user_register.cleaned_data.get('username')
            email=user_register.cleaned_data.get('email')
            password=user_register.cleaned_data.get('password1')
            user=User.objects.create(username=username,email=email,password=password)
            user.set_password(user.password)
            user.save()
            registred=True
            return HttpResponseRedirect(reverse('index'))
        else:
            return HttpResponse('there is a problem')
    else:
        return render(request,'register.html',{'registred':registred,'user_register':RegisterForm})


def user_login(request):
    if request.method=='POST':
        email=request.POST.get('email')
        password=request.POST.get('password')

        user=authenticate(email=email,password=password)

        if user is not None:
            return HttpResponseRedirect(reverse('index'))
        else:
            return HttpResponse("Account not found")
    else:
        return render(request,'login.html')

#user-logout view
@login_required
def user_logout(request):
    logout(request)
    return HttpResponseRedirect(reverse('index'))

#registration view

forms.py:

# accounts.forms.py
from django import forms
from django.contrib.auth.forms import ReadOnlyPasswordHashField

from .models import User


class RegisterForm(forms.ModelForm):
    password = forms.CharField(widget=forms.PasswordInput)
    password2 = forms.CharField(label='Confirm password', widget=forms.PasswordInput)

    class Meta:
        model = User
        fields = ('email','username','full_name','short_name','password')

    def clean_username(self):
        username = self.cleaned_data.get('username')
        if User.objects.filter(username__iexact=username).exists():
            raise forms.ValidationError('This username already exists')
        return username

    def clean_email(self):
        email = self.cleaned_data.get('email')
        qs = User.objects.filter(email=email)
        if qs.exists():
            raise forms.ValidationError("email is taken")
        return email

    def clean_password2(self):

        password1 = self.cleaned_data.get("password1")
        password2 = self.cleaned_data.get("password2")
        if password1 and password2 and password1 != password2:
            raise forms.ValidationError("Passwords don't match")
        return password2


class UserAdminCreationForm(forms.ModelForm):

    password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
    password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput)

    class Meta:
        model = User
        fields = ('email',)

    def clean_password2(self):

        password1 = self.cleaned_data.get("password1")
        password2 = self.cleaned_data.get("password2")
        if password1 and password2 and password1 != password2:
            raise forms.ValidationError("Passwords don't match")
        return password2

    def save(self, commit=True):

        user = super(UserAdminCreationForm, self).save(commit=False)
        user.set_password(self.cleaned_data["password1"])
        if commit:
            user.save()
        return user


class UserAdminChangeForm(forms.ModelForm):

    password = ReadOnlyPasswordHashField()

    class Meta:
        model = User
        fields = ('email', 'password', 'active', 'admin')

    def clean_password(self):

        return self.initial["password"]

models.py

# accounts.models.py

from django.db import models
from django.contrib.auth.models import (
    BaseUserManager, AbstractBaseUser
)

# accounts.models.py

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

        user = self.model(
            email=self.normalize_email(email),
        )

        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_staffuser(self, email, password):
        """
        Creates and saves a staff user with the given email and password.
        """
        user = self.create_user(
            email,
            password=password,
        )
        user.staff = True
        user.save(using=self._db)
        return user

    def create_superuser(self, email, password):
        """
        Creates and saves a superuser with the given email and password.
        """
        user = self.create_user(
            email,
            password=password,
        )
        user.staff = True
        user.admin = True
        user.save(using=self._db)
        return user

# hook in the New Manager to our Model



class User(AbstractBaseUser):
    email = models.EmailField(
        verbose_name='email address',
        max_length=255,
        unique=True,
    )
    username=models.CharField(default='',unique=True,max_length=50)
    full_name=models.CharField(default='',max_length=50)
    short_name=models.CharField(default='',max_length=50)
    active = models.BooleanField(default=True)
    staff = models.BooleanField(default=False) # a admin user; non super-user
    admin = models.BooleanField(default=False) # a superuser
    # notice the absence of a "Password field", that is built in.

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = [] # Email & Password are required by default.

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

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

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

    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?"
        return self.staff

    @property
    def is_admin(self):
        "Is the user a admin member?"
        return self.admin

    @property
    def is_active(self):
        "Is the user active?"
        return self.active
    objects = UserManager()

【问题讨论】:

  • 你能分享你的模型吗?

标签: python django django-models django-forms django-registration


【解决方案1】:

我刚刚将这个 password=user_register.cleaned_data.get('password') 更改为这个 password=request.POST.get('password') 并且它起作用了

【讨论】:

    猜你喜欢
    • 2019-01-21
    • 2014-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-31
    • 1970-01-01
    • 2015-04-22
    • 2018-08-24
    相关资源
    最近更新 更多