NOT NULL约束失败的原因是什么:generalpage_userregister.user_id是什么意思?在我的



我正试图使用Django创建一个网站,但遇到了一个问题,我已经挣扎了几个小时。有人能解释我收到的原因吗

NOT NULL约束失败:generalpage_userregister.user_id

错误以及如何解决此问题?

我怀疑这与pk有关,但我无法理解这一点。

我正在尝试创建一个自定义模型,当我试图创建一个超级用户时,我会收到上面提到的错误。

我的观点是:

page = "create-account"
form = UserRegisterForm()

if request.method == "POST":
form = UserRegisterForm(request.POST)
if form.is_valid():
userRegister = form.save(commit=False)
userRegister.user = request.user(id=pk)
#user.username = user.username.lower()
userRegister.save()

#login(request, userRegister)
return redirect("generalpage:home-page")
else:
form = UserRegisterForm()

context = {"form": form, "page": page}
return render(request, "generalpage/create_account.html", context) ```
My urls are:
``` from django.urls import path
from . import views
app_name = "generalpage"
urlpatterns = [
path("hem/", views.home, name="home-page"),

path("registrering/", views.registerprofile, name="register-page"),

path("logga-in/", views.loginpage, name="login-page"),
path("logga-ut", views.logoutuser, name="logoutuser"),

path("skapa-annons/", views.createroom, name="createroom-page"),
path("skapa-konto/<str:pk>/", views.createaccount, name="createaccount-page"),

path("radera-rum/", views.deleteroom, name="deleteroom"),
path("uppdatera-rum/", views.updateroom, name="updateroom"), 
] ```
the models is:
``` from datetime import datetime
import email
from email import message
from email.policy import default
from enum import unique
from pyexpat import model
from wsgiref.validate import validator
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, User, PermissionsMixin
from django.utils import timezone
from django.utils.translation import gettext_lazy as _
from . managers import UserRegisterManager
from django.conf import settings
# Create your models here.
class UserRegister(AbstractBaseUser, PermissionsMixin):
user = models.OneToOneField(settings.AUTH_USER_MODEL, blank=True, on_delete=models.CASCADE)
username = models.CharField(_("Användarnamn"), max_length=100, null=True, unique=True)
age = models.IntegerField()
email = models.EmailField(unique=True, null=False)

country = models.CharField(max_length=50)
county = models.CharField(max_length=50)
city = models.CharField(max_length=50)
profile_picture = models.ImageField(null=True, default="avatar.svg")

is_staff = models.BooleanField(default=False)
is_active = models.BooleanField(default=False)
date_joined = models.DateTimeField(default=timezone.now)
USERNAME_FIELD = 'username' # defines the unique identifier for the User model
REQUIRED_FIELDS = ["email"] # A list of the field names that will be prompted for when creating a user via the createsuperuser management command

objects = UserRegisterManager()

def __str__(self):
return self.username ```
The form is:
``` from dataclasses import field, fields
from django import forms 
from .models import User, UserInfo, Room, UserRegister
from generalpage import models
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
# User register account page
class UserRegisterForm(UserCreationForm):
class Meta:
model = UserRegister
exclude = ["password", "last_login"]
#fields = "__all__" ```
The user manager that I've created is:
``` from django.contrib.auth.base_user import BaseUserManager
from django.utils.translation import gettext_lazy as _

class UserRegisterManager(BaseUserManager):
"""
Custom user model manager where username is the unique identifiers
for authentication instead of usernames.
"""
def create_user(self, email, username, password, **extra_fields):
"""
Create and save a User with the given username and password.
"""
if not username:
raise ValueError(_('Du måste ange ett användarnamn'))
if not email:
raise ValueError(_('Du måste ange ett email'))
if not password:
raise ValueError(_('Du måste ange ett lösenord'))

email = self.normalize_email(email)
user = self.model(username=username, email=email, password=password, **extra_fields)
user.set_password(password)
user.save()
return user
def create_superuser(self, email, username, password, **extra_fields):
"""
Create and save a SuperUser with the given username and password.
"""
extra_fields.setdefault('is_staff', True)
extra_fields.setdefault('is_superuser', True)
extra_fields.setdefault('is_active', True)
if extra_fields.get('is_staff') is not True:
raise ValueError(_('Superanvändare måste ha is_staff=True.'))
if extra_fields.get('is_superuser') is not True:
raise ValueError(_('Superanvändare måste ha is_superuser=True.'))

return self.create_user(username, email, password, **extra_fields) 

我的设置是:

Django settings for sx_site project.
Generated by 'django-admin startproject' using Django 4.1.
For more information on this file, see
https://docs.djangoproject.com/en/4.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.1/ref/settings/
"""
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-c__5bvtpvm)k71%n=+@&y4&2#n883)xj=!77ujo5-4krdeuouk'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []

# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',

'generalpage.apps.GeneralpageConfig',
'profilesettings.apps.ProfilSettingsConfig',
'trainingApp.apps.TrainingappConfig',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'sx_site.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'sx_site.wsgi.application'

# Database
# https://docs.djangoproject.com/en/4.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}

# Password validation
# https://docs.djangoproject.com/en/4.1/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]

# Internationalization
# https://docs.djangoproject.com/en/4.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.1/howto/static-files/
STATIC_URL = 'static/'
STATICFILES_DIRS = [
BASE_DIR / "static"
]
# Default primary key field type
# https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
AUTH_USER_MODEL = 'generalpage.UserRegister'

您在创建UserRegister对象时没有指定user字段。这是不可能的,因为你有:

user = models.OneToOneField(settings.AUTH_USER_MODEL, blank=True, on_delete=models.CASCADE)

这里不排除user字段:

model = UserRegister
exclude = ["password", "last_login"]

只需添加"user"即可排除。

相关内容

  • 没有找到相关文章

最新更新