Hi All,
I’m pretty much new to Django and Python. Trying to build a Web Application and currently Stuck at below error can someone please guide on resolving this.
Error
Exception in thread django-main-thread:
Traceback (most recent call last):
File "/Users/Kiran.Thota/.pyenv/versions/3.10.2/lib/python3.10/threading.py", line 1009, in _bootstrap_inner
self.run()
File "/Users/Kiran.Thota/.pyenv/versions/3.10.2/lib/python3.10/threading.py", line 946, in run
self._target(*self._args, **self._kwargs)
File "/Applications/Training/Project_Amplify/venv/lib/python3.10/site-packages/django/utils/autoreload.py", line 64, in wrapper
fn(*args, **kwargs)
File "/Applications/Training/Project_Amplify/venv/lib/python3.10/site-packages/django/core/management/commands/runserver.py", line 134, in inner_run
self.check(display_num_errors=True)
File "/Applications/Training/Project_Amplify/venv/lib/python3.10/site-packages/django/core/management/base.py", line 486, in check
all_issues = checks.run_checks(
File "/Applications/Training/Project_Amplify/venv/lib/python3.10/site-packages/django/core/checks/registry.py", line 88, in run_checks
new_errors = check(app_configs=app_configs, databases=databases)
File "/Applications/Training/Project_Amplify/venv/lib/python3.10/site-packages/django/core/checks/urls.py", line 44, in check_url_namespaces_unique
all_namespaces = _load_all_namespaces(resolver)
File "/Applications/Training/Project_Amplify/venv/lib/python3.10/site-packages/django/core/checks/urls.py", line 63, in _load_all_namespaces
url_patterns = getattr(resolver, "url_patterns", [])
File "/Applications/Training/Project_Amplify/venv/lib/python3.10/site-packages/django/utils/functional.py", line 47, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/Applications/Training/Project_Amplify/venv/lib/python3.10/site-packages/django/urls/resolvers.py", line 718, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "/Applications/Training/Project_Amplify/venv/lib/python3.10/site-packages/django/utils/functional.py", line 47, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/Applications/Training/Project_Amplify/venv/lib/python3.10/site-packages/django/urls/resolvers.py", line 711, in urlconf_module
return import_module(self.urlconf_name)
File "/Users/Kiran.Thota/.pyenv/versions/3.10.2/lib/python3.10/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1050, in _gcd_import
File "<frozen importlib._bootstrap>", line 1027, in _find_and_load
File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 688, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 883, in exec_module
File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
File "/Applications/Training/Project_Amplify/quiz/quiz/urls.py", line 19, in <module>
from django.contrib.auth import views as auth_views
File "/Applications/Training/Project_Amplify/venv/lib/python3.10/site-packages/django/contrib/auth/views.py", line 11, in <module>
from django.contrib.auth.forms import (
File "/Applications/Training/Project_Amplify/venv/lib/python3.10/site-packages/django/contrib/auth/forms.py", line 6, in <module>
from django.contrib.auth.models import User
File "/Applications/Training/Project_Amplify/venv/lib/python3.10/site-packages/django/contrib/auth/models.py", line 7, in <module>
from django.contrib.contenttypes.models import ContentType
File "/Applications/Training/Project_Amplify/venv/lib/python3.10/site-packages/django/contrib/contenttypes/models.py", line 134, in <module>
class ContentType(models.Model):
File "/Applications/Training/Project_Amplify/venv/lib/python3.10/site-packages/django/db/models/base.py", line 134, in __new__
raise RuntimeError(
**RuntimeError: Model class django.contrib.contenttypes.models.ContentType doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS.**
settings.py
import os
from pathlib import Path
from django.core.wsgi import get_wsgi_application
# 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/5.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-secret_key'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "PyQuiz.settings")
application = get_wsgi_application()
os.environ["DJANGO_ALLOW_ASYNC_UNSAFE"] = "true"
import django
django.setup()
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'PyQuiz.apps.PyquizConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'allauth.account',
'allauth.account.utils',
]
ROOT_URLCONF = 'quiz.urls'
### adding AUTH_USER_MODEL for Custom Model
AUTH_USER_MODEL = "PyQuiz.User"
code in apps.py
from django.apps import AppConfig
class PyquizConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'PyQuiz'
verbose_name="Python Quiz"
class Meta:
app_label = "PyQuiz"
code in admin.py
from django.contrib import admin
from django.contrib.auth import get_user_model
# from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from .models import User, Profile
# Register your models here.
class UserAdmin(BaseUserAdmin):
fieldsets =(
(None, {"fields": ("email", "password", "name", "last_login")}),
("Permissions", {"fields" : (
"is_active",
"is_staff",
"is_superuser",
"groups",
"user_permissions",
)}),
)
add_fieldsets=(
(
None,
{
"classes" : ("wide",),
"fields" : ("email", "password1", "password2")
}
),
)
list_display =("email", "name", "is_staff", "last_login")
list_filter = ("is_staff", "is_superuser", "is_active", "groups")
search_fields = ("email",)
ordering = ("email",)
filter_horizontal = ("groups", "user_permissions",)
admin.site.register(User, UserAdmin)
admin.site.register(Profile)
Code in models.py
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin
from django.utils import timezone
from django.db.models.signals import post_save
from django.dispatch import receiver
from PIL import Image
class Address(models.Model):
name = models.CharField(max_length=30)
address = models.CharField(max_length=50)
city = models.CharField(max_length=60, default="")
state = models.CharField(max_length=30, default="")
postcode = models.CharField(max_length=6, default="")
country = models.CharField(max_length=50)
class Meta:
verbose_name = "Address"
verbose_name_plural = " Address"
# app_label = "PyQuiz"
def __str__(self):
return self.name
class UserManager(BaseUserManager):
def _create_user(self, email, password, is_staff, is_superuser, **extra_fields):
if not email:
raise ValueError("Users must have an email address")
now = timezone.now()
email = self.normalize_email(email)
user = self.model(
email = email,
is_staff = is_staff,
is_active = True,
is_superuser = is_superuser,
last_login = now,
date_joined= now,
**extra_fields
)
user.set_password(password)
user.save(using=self._db)
return user
def create_user(self, email, password, **extra_fields):
return self._create_user(email, password, True, True, **extra_fields)
def create_superuser(self, email, password, **extra_fields):
user = self._create_user(email, password, True, True, **extra_fields)
user.save(using= self._db)
return user
# class Meta:
# app_label = "PyQuiz"
class User(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(max_length=254, unique=True)
name = models.CharField(max_length=254, null= True, blank= True)
username = models.CharField(max_length=254, null=True, blank=True)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
last_login = models.DateTimeField(null=True, blank=True)
date_joined = models.DateTimeField(auto_now_add=True)
USERNAME_FIELD = "email"
EMAIL_FIELD = "email"
REQUIRED_FIELDS = []
objects = UserManager()
def get_absolute_url(self):
return "/users/%i/" % (self.pk)
class Profile(models.Model):
user = models.OneToOneField(User, unique=True, on_delete=models.CASCADE, default=None)
address = models.CharField(max_length=254, null=True, blank=True)
image = models.ImageField(default="default.jpg", upload_to="profile_pics")
def __str__(self):
return f"{self.user.name} Profile"
def save(self, *args, **kwargs):
super.save(*args, **kwargs)
@receiver(post_save, sender= User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwards):
instance.profile.save()