django.db.utils.OperationalError:no such table:auth_user; but works with django admin

uinbv5nw  于 12个月前  发布在  Go
关注(0)|答案(1)|浏览(161)

修复:我从django.contrib.auth.models.User导入User模型,忘记将其替换为.models.User

我是Django的初学者,学习如何在我的账户应用程序中使用abstractuser创建自定义用户模型。但是在创建注册系统时,我遇到了这个问题:django.db.utils.OperationalError:no such table:auth_user

Request URL: http://localhost:8000/accounts/register/

Django Version: 4.2.6

Python Version: 3.11.6

Installed Applications:

['django.contrib.admin',

 'django.contrib.auth',

 'django.contrib.contenttypes',

 'django.contrib.sessions',

 'django.contrib.messages',

 'django.contrib.staticfiles',

 'accounts.apps.AccountsConfig']

Installed 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']

Traceback (most recent call last):

  File "/data/data/com.termux/files/usr/lib/python3.11/site-packages/django/db/backends/utils.py", line 89, in _execute

    return self.cursor.execute(sql, params)

           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

  File "/data/data/com.termux/files/usr/lib/python3.11/site-packages/django/db/backends/sqlite3/base.py", line 328, in execute

    return super().execute(query, params)

           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

The above exception (no such table: auth_user) was the direct cause of the following exception:

  File "/data/data/com.termux/files/usr/lib/python3.11/site-packages/django/core/handlers/exception.py", line 55, in inner

    response = get_response(request)

               ^^^^^^^^^^^^^^^^^^^^^

  File "/data/data/com.termux/files/usr/lib/python3.11/site-packages/django/core/handlers/base.py", line 197, in _get_response

    response = wrapped_callback(request, *callback_args, **callback_kwargs)

               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

  File "/data/data/com.termux/files/usr/lib/python3.11/site-packages/django/views/generic/base.py", line 104, in view

    return self.dispatch(request, *args, **kwargs)

           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

  File "/data/data/com.termux/files/usr/lib/python3.11/site-packages/django/views/generic/base.py", line 143, in dispatch

    return handler(request, *args, **kwargs)

           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

  File "/data/data/com.termux/files/home/qrkeeper/accounts/views.py", line 55, in post

    user.save()

    ^^^^^^^^^^^

  File "/data/data/com.termux/files/usr/lib/python3.11/site-packages/django/contrib/auth/base_user.py", line 76, in save

    super().save(*args, **kwargs)

    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

  File "/data/data/com.termux/files/usr/lib/python3.11/site-packages/django/db/models/base.py", line 814, in save

    self.save_base(

    ^

  File "/data/data/com.termux/files/usr/lib/python3.11/site-packages/django/db/models/base.py", line 877, in save_base

    updated = self._save_table(

              

  File "/data/data/com.termux/files/usr/lib/python3.11/site-packages/django/db/models/base.py", line 1020, in _save_table

    results = self._do_insert(

              

  File "/data/data/com.termux/files/usr/lib/python3.11/site-packages/django/db/models/base.py", line 1061, in _do_insert

    return manager._insert(

           

  File "/data/data/com.termux/files/usr/lib/python3.11/site-packages/django/db/models/manager.py", line 87, in manager_method

    return getattr(self.get_queryset(), name)(*args, **kwargs)

           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

  File "/data/data/com.termux/files/usr/lib/python3.11/site-packages/django/db/models/query.py", line 1805, in _insert

    return query.get_compiler(using=using).execute_sql(returning_fields)

           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

  File "/data/data/com.termux/files/usr/lib/python3.11/site-packages/django/db/models/sql/compiler.py", line 1822, in execute_sql

    cursor.execute(sql, params)

    ^^^^^^^^^^^^^^^^^^^^^^^^^^^

  File "/data/data/com.termux/files/usr/lib/python3.11/site-packages/django/db/backends/utils.py", line 102, in execute

    return super().execute(sql, params)

           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^

  File "/data/data/com.termux/files/usr/lib/python3.11/site-packages/django/db/backends/utils.py", line 67, in execute

    return self._execute_with_wrappers(

           

  File "/data/data/com.termux/files/usr/lib/python3.11/site-packages/django/db/backends/utils.py", line 80, in _execute_with_wrappers

    return executor(sql, params, many, context)

           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

  File "/data/data/com.termux/files/usr/lib/python3.11/site-packages/django/db/backends/utils.py", line 84, in _execute

    with self.db.wrap_database_errors:

    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

  File "/data/data/com.termux/files/usr/lib/python3.11/site-packages/django/db/utils.py", line 91, in __exit__

    raise dj_exc_value.with_traceback(traceback) from exc_value

    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

  File "/data/data/com.termux/files/usr/lib/python3.11/site-packages/django/db/backends/utils.py", line 89, in _execute

    return self.cursor.execute(sql, params)

           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

  File "/data/data/com.termux/files/usr/lib/python3.11/site-packages/django/db/backends/sqlite3/base.py", line 328, in execute

    return super().execute(query, params)

           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Exception Type: OperationalError at /accounts/register/

Exception Value: no such table: auth_user```

My accounts/views.py 's register view:

字符串
类寄存器(视图):

def get(self, request):

    if request.user.is_authenticated:

        messages.info(request, "You are already logged in")

        return redirect("index")

    return render(request, "accounts/register.html")

def post(self, request):

    passwd1 = request.POST.get("password1", "")

    passwd2 = request.POST.get("password2", "")

    if passwd1 != passwd2:

        messages.warning(request, "Password not match")

        return redirect("accounts:register")

    email = request.POST.get("email", "")

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

    if user is None:

        user = User(email=email)

        user.set_password(passwd1)

        user.save()

        messages.success(request, "User created")

        return redirect("accounts:login")

    else:

        messages.info(request, "User already exists.")

        return redirect("accounts:register")```


用户模型(accounts/models.py):

from django.contrib.auth.models import AbstractUser
from django.db import models
from django.utils.translation import gettext as _
from .managers import UserManager

class User(AbstractUser):
    username = None
    email = models.EmailField(_('email address'), unique=True)

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []

    objects = UserManager()

    def __str__(self):
        return f'User({self.id}, "{self.email}")'


账户/managers.py

from django.contrib.auth.base_user import BaseUserManager
from django.utils.translation import gettext as _

class UserManager(BaseUserManager):
    """
    Custom user model manager.
    """
    use_in_migration = True

    def create_user(self, email, password, **extra_fields):
        if not email:
            raise ValueError(_('Users must have an email'))
        email = self.normalize_email(email)
        user = self.model(email=email, **extra_fields)
        user.set_password(password)
        user.save()
        return user

    def create_superuser(self, email, password, **extra_fields):
        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(_('Superuser must have is_staff=True.'))
        if extra_fields.get('is_superuser') is not True:
            raise ValueError(_('Superuser must have is_superuser=True.'))
        return self.create_user(email, password, **extra_fields)


我的settings.py

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.2/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'something_secret'

# 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',
]

EXTERNAL_APPS = [
    'accounts.apps.AccountsConfig',
    'shorturl.apps.ShorturlConfig',
]

INSTALLED_APPS += EXTERNAL_APPS

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 = 'qrkeeper.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [BASE_DIR/"templates"],
        '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 = 'qrkeeper.wsgi.application'

# Database
# https://docs.djangoproject.com/en/4.2/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}

# Password validation
# https://docs.djangoproject.com/en/4.2/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.2/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.2/howto/static-files/

STATIC_URL = 'static/'
STATICFILES_DIRS = [
    BASE_DIR / "static"
]

# Default primary key field type
# https://docs.djangoproject.com/en/4.2/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

AUTH_USER_MODEL = "accounts.User"


我所尝试的:

  1. python manage.py makemigrations && python manage.py migrate
    1.从我的帐户应用程序中删除迁移文件。并再次按照第1步
    当我尝试使用django superuser、django Admin和django shell创建用户时,它完美地工作,没有任何错误。只有当我在注册表视图中调用保存()时才会发生错误。

修复:我从django.contrib.auth.models.User导入User模型,忘记将其替换为.models.User

qxgroojn

qxgroojn1#

您是否在settings.py?“AUTH_USER_MODEL = 'accounts.User'“中指定了新用户

相关问题