在使用信号时出现错误,Django无法识别内置的User模型的app_label。

14 浏览
0 Comments

在使用信号时出现错误,Django无法识别内置的User模型的app_label。

我正在学习Django信号,并尝试使用一个简单的信号来在创建新用户(默认为Django User模型)后直接创建个人资料。但是,每当我尝试运行服务器时,我都会收到以下错误:

RuntimeError: Model class django.contrib.contenttypes.models.ContentType doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS.

但是:django.contrib.contenttypes已在INSTALLED_APPS中

我是个新手,卡住了.....

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'bootstrapform',
    'basic',
]
# urls
"""Filmweb URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/3.2/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from django.contrib.auth import views as auth_views
from basic.views import Main, ActorsListView, ActorModifyView, ActorCreateView, \
    ActorDeleteView, Films, FilmCreateView, FilmModifyView, FilmDeleteView, Register, RateIt, FilmDetails, Profile, \
    RolesView, RoleModifyView, RestFilmView
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
    path('admin/', admin.site.urls, name='admin'),
    path('main/', Main.as_view(), name='Main'),
    path('films/', Films.as_view(), name='Films'),
    path('films/add', FilmCreateView.as_view(), name='Films_add'),
    path('films/modify/', FilmModifyView.as_view(), name='Films_modify'),
    path('films/delete/', FilmDeleteView.as_view(), name='Films_delete'),
    path('films/details/', FilmDetails.as_view(), name='Films_details'),
    path('rate/', RateIt.as_view(), name="Rate"),
    path('rest/', RestFilmView.as_view(), name="Rate"),
    path('actors/', ActorsListView.as_view(), name='Actors'),
    path('actors/add/', ActorCreateView.as_view(), name='Actors_add'),
    path('actor/modify//', ActorModifyView.as_view(), name='Actor_modify'),
    path('actor/delete//', ActorDeleteView.as_view(), name='Actor_delete'),
    path('roles/', RolesView.as_view(), name='Roles'),
    path('roles/modify/', RoleModifyView.as_view(), name='Role_modify'),
    # path('actor/modify//', ActorModifyView.as_view(), name='Actor_modify'),
    path('login/', auth_views.LoginView.as_view(), name="Login"),
    path('logout/', auth_views.LogoutView.as_view(), name="Logout"),
    path('register/', Register.as_view(), name="Register"),
    path('profile/', Profile.as_view(), name="Profile"),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
#admin 
from django.contrib import admin
from .models import *
# Register your models here.
# @admin.register(Films)
# class FilmAdmin(admin.ModelAdmin):
#     fields = ['title', 'description', 'premiere', 'imdb_rating', 'genre']
#     list_display = ['title', 'description', 'premiere', 'imdb_rating', 'genre']
#     list_filter = ("premiere", "imdb_rating", 'genre')
#     search_fields = ("title", "description", "premiere", 'genre')
admin.site.register(Genre)
admin.site.register(Films)
admin.site.register(Actors)
admin.site.register(Roles)
# admin.site.register(RoleReviews)
admin.site.register(FilmReviews)
# admin.site.register(Profiles)
# admin.site.register(Directors)
# admin.site.register(Messages)
# apps.py
from django.apps import AppConfig
from django.contrib.auth.models import User
class UsersConfig(AppConfig):
    name = 'basic'
    def ready(self):
        import basic.signals
# signals.py
from django.db.models.signals import post_save
from django.contrib.auth.models import User
from django.dispatch import receiver
from .models import Profile
@receiver(post_save, sender=User)
def build_profile(sender, instance, created, **kwargs):
    if created:
        Profile.objects.create(user=instance)
@receiver(post_save, sender=User)
def save_profile(sender, instance, **kwargs):
    instance.profile.save()
# models 
from pyexpat import model
from django.db import models
from django.core.validators import MinValueValidator, MaxValueValidator
from django.contrib.auth.models import User
# Create your models here.
class Genre(models.Model):
    # 0 = 'Undefined'
    # 1 = 'SO'
    # 2 = 'JR'
    # 3 = 'SR'
    # 4 = 'GR'
    # YEAR_IN_SCHOOL_CHOICES = [
    #     (FRESHMAN, 'Freshman'),
    #     (SOPHOMORE, 'Sophomore'),
    #     (JUNIOR, 'Junior'),
    #     (SENIOR, 'Senior'),
    #     (GRADUATE, 'Graduate'),
    # ]
    MOVIE_TYPE = {
        (0, 'Undefined'),
        (1, 'Comedy'),
        (2, 'Drama'),
        (3, 'Sci-fi'),
        (4, 'action'),
        (5, 'romantic'),
        (6, 'rom-coms'),
        (7, 'adventure'),
        (8, 'musicals'),
    }
    name = models.PositiveSmallIntegerField(default=0, choices=MOVIE_TYPE)
    def show_genre(self):
        if self.name == 0:
            return 'Undefined'
        elif self.name == 1:
            return 'Comedy'
        elif self.name == 2:
            return 'Drama'
        elif self.name == 3:
            return 'Sci-fun'
        elif self.name == 4:
            return 'Action'
        elif self.name == 5:
            return 'Romantic'
        elif self.name == 6:
            return 'Rom-coms'
        elif self.name == 7:
            return 'Adventure'
        elif self.name == 8:
            return 'Musiclas'
    def __str__(self):
        return f'{self.show_genre()}'
class Films(models.Model):
    title = models.CharField(max_length=64, blank=False, unique=True)
    description = models.TextField(default="")
    premiere = models.DateField(null=True, blank=True)
    duration = models.PositiveSmallIntegerField(default=0)
    imdb_rating = models.DecimalField(max_digits=4, decimal_places=2, null=True, blank=True)
    genre = models.ForeignKey(Genre, on_delete=models.CASCADE, null=True, blank=True)
    # directed_by = models.ForeignKey("Directors", null=False, blank=False, on_delete=models.CASCADE)
    poster = models.ImageField(upload_to='posters', null=True, blank=True)
    roles = models.ManyToManyField("Actors", through='Roles', related_name='role')
    film_reviews = models.ManyToManyField(User, through='FilmReviews')
    def __str__(self):
        return self.title_with_year()
    def title_with_year(self):
        return f"{self.title} ({self.premiere})"
    def total_seen(self):
        return FilmReviews.objects.filter(seen=True, film=self).count()
class Actors(models.Model):
    name = models.CharField(max_length=32)
    surname = models.CharField(max_length=32)
    photo = models.ImageField(upload_to='actors', null=True, blank=True)
    def __str__(self):
        return f"{self.name} {self.surname}"
class Roles(models.Model):
    film = models.ForeignKey(Films, on_delete=models.CASCADE, related_name='film_title')
    actor = models.ForeignKey(Actors, on_delete=models.CASCADE, related_name='actor_role')
    role_name = models.CharField(max_length=64, null=False, blank=False)
    # role_photo = models.ImageField(upload_to='roles', null=True, blank=True)
    # role_review = models.ManyToManyField(User, through='RoleReviews')
    def __str__(self):
        return f"{self.film.title} {self.actor.name} {self.actor.surname}"
class FilmReviews(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='User_FilmReviews')
    film = models.ForeignKey(Films, on_delete=models.CASCADE)
    user_rating = models.DecimalField(max_digits=4, decimal_places=2, null=False, blank=False)
    user_review = models.TextField(null=True, blank=True)
    seen = models.BooleanField(default=True)
class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    image = models.ImageField(default='profilepic.jpg', upload_to='profiles', null=True, blank=True)
    location = models.CharField(max_length=100, default='Not your business')
    def __str__(self):
        return self.user.username

0