R
R
recursy2022-03-30 14:32:27
Django
recursy, 2022-03-30 14:32:27

How to fix error when creating user abstract class in DJANGO?

I added AbstractUser to the user model and after that the registration on the site failed, it gives the following error when submitting the registration form:

Manager isn't available; 'auth.User' has been swapped for 'mainsite.ProjectUser'

(Login works, users are created in the admin panel, other models work properly, and so on) I
created an abstract user according to the documentation at the very beginning of the project without any migrations.

models.py file
from django.db import models
from django.contrib.auth.models import AbstractUser
from django.contrib.auth import get_user_model


class ProjectUser(AbstractUser):
    def __str__(self):
        return self.username

    class Meta:
        abstract = False


class Article_filmss(models.Model):
    title = models.CharField(max_length=255)
    year_pub_date = models.CharField(max_length=4)
    quality_video = models.CharField(max_length=10)
    age_for = models.CharField(max_length=4)
    producer = models.CharField(max_length=23)
    film_budget = models.CharField(max_length=15)
    film_genre = models.CharField(max_length=31)
    movie_duration = models.CharField(max_length=10)
    content = models.TextField()
    img = models.ImageField(upload_to='media')
    video = models.FileField(upload_to='media', blank=True, null=True)
    favorite = models.ManyToManyField(ProjectUser, related_name='fav_films', blank=True)

    def __str__(self):
        return self.title


User = get_user_model()


views.py
from django.http import HttpResponseRedirect
from django.shortcuts import render, redirect, get_object_or_404
from mainsite.models import Article_filmss
from mainsite.forms import Login_form
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth import get_user_model
from django.contrib.auth.forms import UserCreationForm


def main_heading(request):
    article = Article_filmss.objects.all()
    return render(request, 'mainsite/article.html', {'article': article})


def detail(request, question_id):
    article = Article_filmss.objects.get(pk=question_id)
    return render(request, 'mainsite/detail.html', {'article': article})


def new_funct(request):
    if request.method == 'POST':
        user_request = None
        objects_list = None
    else:
        user_request = request.GET.get('search')
        objects_list = Article_filmss.objects.filter(title__icontains=user_request)
    return render(request, 'mainsite/search_results.html',
                  {'objects_list': objects_list, 'user_request': user_request})


def login_user(request):
    if request.method == 'POST':
        form = Login_form(request.POST)

        if form.is_valid():
            user_name = form.cleaned_data['user_name']
            password = form.cleaned_data['password']

            user = authenticate(username=user_name, password=password)
            if user:
                login(request, user)
                return HttpResponseRedirect('/main')
    else:
        form = Login_form()

    context = {
        'form': form,
    }
    return render(request, 'mainsite/login.html', context)


def register(request):
    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        if form.is_valid():
            user = form.save()
            login(request, user)
            return HttpResponseRedirect('/main')
        else:
            print(form.errors)
    else:
        form = UserCreationForm()
    password_error1 = form['password1'].errors
    password_error2 = form['password2'].errors
    user_error = form['username'].errors
    return render(request, 'mainsite/register.html', {'form': form, 'password_error1': password_error1,
                                                       'password_error2': password_error2, 'user_error': user_error})


def logout_view(request):
    logout(request)
    return redirect('/main/')


def favourite_post(request, question_id):
    article = Article_filmss.objects.get(pk=question_id)
    video = get_object_or_404(Article_filmss, id=question_id)
    if request.method == 'POST':
        video.favorite.add(request.user)
        return HttpResponseRedirect(f'/main/{question_id}')


User = get_user_model()


forms.py
from django import forms
from django.contrib.auth import get_user_model


class Login_form(forms.Form):
    user_name = forms.CharField()
    password = forms.CharField()


User = get_user_model()


setting.py
"""
Django settings for kinamefilm project.

Generated by 'django-admin startproject' using Django 4.0.3.

For more information on this file, see
https://docs.djangoproject.com/en/4.0/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.0/ref/settings/
"""

from pathlib import Path
import os
import sys
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
PROJECT_ROOT = os.path.dirname(__file__)

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure--8*17!j2f5(3(p*81i+go(_+btl-f1y6osu8_393*#yq*vr6&n'

# 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',
    'mainsite.apps.MainsiteConfig',

]

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

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
                os.path.join(PROJECT_ROOT, '../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 = 'kinamefilm.wsgi.application'


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

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'kinamefilmsql',
        'USER': 'admin',
        'PASSWORD': 'admin',
        'HOST': '127.0.0.1',
        'PORT': '5432',
    }
}



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

STATIC_URL = 'static/'

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

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
STATICFILES_DIRS = [
    os.path.join(PROJECT_ROOT, '../static'),
]
MEDIA_ROOT = os.path.join(BASE_DIR, '').replace('\\', '/')
MEDIA_URL = 'media/'
AUTH_USER_MODEL = 'mainsite.ProjectUser'


admin.py
from django.contrib import admin
from .models import Article_filmss
from django.contrib.auth.admin import UserAdmin
from .models import ProjectUser

admin.site.register(ProjectUser, UserAdmin)
admin.site.register(Article_filmss)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
rekursy, 2022-03-30
@rekursy

PS User at the end did according to the tutorials, but all in vain.

D
Danil Gorev, 2022-03-30
@ketovv

Can you trace the error please?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question