TinyMCE not showing up in Django admin - django

I was just trying out tinymce. It worked well with the default config (I didn't put anything in the config). Later I found a few configs on the web and copy pasted them into the settings, and it worked fine. However upon copy pasting another config, the TinyMCE form doesn't seem to be displaying.
My web app is a blog post.
My settings.py
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'sid&6o(*h*r!9p+gs-++chd+c(8(awc^u6*1yia5s8a^csmgip'
# 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',
'posts',
'marketing',
'tinymce',
]
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 = 'bootstrapblog.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join('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 = 'bootstrapblog.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/3.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/3.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static_in_env')]
VENV_PATH = os.path.dirname(BASE_DIR)
STATIC_ROOT = os.path.join(VENV_PATH, 'static_root')
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(VENV_PATH, 'media_root')
# Tiny MCE
TINYMCE_DEFAULT_CONFIG = {
'height':
360,
'width':
970,
'cleanup_on_startup':
True,
'custom_undo_redo_levels':
20,
'selector':
'textarea',
'theme':
'modern',
'plugins':
'''
textcolor save link image media preview codesample contextmenu
table code lists fullscreen insertdatetime nonbreaking
contextmenu directionality searchreplace wordcount visualblocks
visualchars code fullscreen autolink lists charmap print hr
anchor pagebreak
''',
'toolbar1':
'''
fullscreen preview bold italic underline | fontselect,
fontsizeselect | forecolor backcolor | alignleft alignright |
aligncenter alignjustify | indent outdent | bullist numlist table |
| link image media | codesample |
''',
'toolbar2':
'''
visualblocks visualchars |
charmap hr pagebreak nonbreaking anchor | code |
''',
'contextmenu':
'formats | link image',
'menubar':
True,
'statusbar':
True,
}
My model for the blog(only relevant parts):
from tinymce.models import HTMLField
class Post(models.Model):
title = models.CharField(max_length=100)
overview = models.TextField()
timestamp = models.DateTimeField(auto_now_add=True)
comment_count = models.IntegerField(default=0)
content = HTMLField()
view_count = models.IntegerField(default=0)
author = models.ForeignKey(Author, on_delete=models.CASCADE)
thumbnail = models.ImageField()
category = models.ManyToManyField(Category)
featured = models.BooleanField()
The form:
from django import forms
from .models import Post
from tinymce import TinyMCE
class PostForm(forms.ModelForm):
content = forms.CharField(
widget=TinyMCE(attrs={
'required': False,
'cols': 30,
'rows': 10
}))
class Meta:
model = Post
fields = '__all__'
All of these were working, till I used the above config. What am I doing wrong?

You need to add url(r'^tinymce/', include('tinymce.urls')), or path('tynymce/', include('tinymce.urls')) to your project urls.py according to http://romanvm.github.io/django-tinymce4-lite/installation.html

For the others: There's a big chances, not being able if you use the incorrect theme, for example in the django-tinymce that I just downloaded, there are only 2 themes "mobile" and "silver", there is no 'modern' theme anymore.
for example: If you change the 'theme': 'silver' in settings.py will work.

Related

django-tinymce doesn't show up in admin

I can't get the django-tinymce module gui to show up in the admin of my django project.
Here's settings.py (tinymce settings are at the end):
import os
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/3.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'XXXXXXXXXXXX'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'notices.apps.NoticesConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.gis',
'imagekit',
'leaflet',
'nested_admin',
'tinymce'
]
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 = 'orag.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 = 'orag.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'xxxxxx',
'NAME': 'xxxxxx',
'USER': 'xxxxxx',
'PASSWORD': 'xxxxxx',
'HOST': 'localhost'
}
}
# Password validation
# https://docs.djangoproject.com/en/3.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/3.1/topics/i18n/
LANGUAGE_CODE = 'fr-FR'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/
STATIC_URL = 'static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
MEDIA_URL = 'media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
# EMAIL_BACKEND = "django.core.mail.backends.filebased.EmailBackend"
# EMAIL_FILE_PATH = str(BASE_DIR.joinpath('sent_emails'))
# print(BASE_DIR)
DEFAULT_AUTO_FIELD = 'django.db.models.AutoField'
# LEAFLET_CONFIG = {
# 'DEFAULT_CENTER': (47.019214, 5.855572),
# 'DEFAULT_ZOOM': 5,
# 'MAX_ZOOM': 20,
# 'MIN_ZOOM':3,
# 'SCALE': 'both',
# 'ATTRIBUTION_PREFIX': 'OrAG'
# }
TINYMCE_JS_URL = STATIC_URL + 'tinymce/tinymce.min.js'
TINYMCE_JS_ROOT = STATIC_ROOT + 'tinymce'
TINYMCE_DEFAULT_CONFIG = {
"height": "320px",
"width": "960px",
"menubar": "file edit view insert format tools table help",
"plugins": "advlist autolink lists link image charmap print preview anchor searchreplace visualblocks code "
"fullscreen insertdatetime media table paste code help wordcount spellchecker",
"toolbar": "undo redo | bold italic underline strikethrough | fontselect fontsizeselect formatselect | alignleft "
"aligncenter alignright alignjustify | outdent indent | numlist bullist checklist | forecolor "
"backcolor casechange permanentpen formatpainter removeformat | pagebreak | charmap emoticons | "
"fullscreen preview save print | insertfile image media pageembed template link anchor codesample | "
"a11ycheck ltr rtl | showcomments addcomment code",
"custom_undo_redo_levels": 10,
"language": "es_ES", # To force a specific language instead of the Django current language.
}
TINYMCE_COMPRESSOR = True
urls.py:
from django.contrib.gis import admin
from django.urls import include, path
from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from django.utils.html import format_html
urlpatterns = [
path('admin/', admin.site.urls),
path('accounts/', include('django.contrib.auth.urls')),
path('notices/', include('notices.urls')),
path('_nested_admin/', include('nested_admin.urls')),
path('tinymce/', include('tinymce.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
And an extract of admin.py (imports and the only model class that will be updated through the admin. I skipped the whole file with Inlines and so on, let me know if it's needed):
class ObjetArchiAdmin(GeoModelAdminMixin, nested_admin.NestedModelAdmin):
formfield_overrides = {
models.TextField: {'widget': TinyMCE()}
}
list_display = ('titre', 'users', 'date', 'id')
fieldsets = (
('État-Civil', {
'fields': (('titre', 'date', 'users'), 'resume')
}),
('Provenance et attribution', {
'fields': ('point', ('prov_pays', 'prov_region'), ('prov_departement', 'prov_ville'), 'lieu_dit', 'attribution')
}),
('Conservation', {
'fields': (('cons_pays', 'cons_region'), ('cons_departement', 'cons_ville'),('cons_depot', 'cons_no_inventaire'), 'cons_localisation')
}),
('Description', {
'fields': ('description', 'contexte', 'observations_comp', ('materiau', 'stuc', 'polychromie'), 'hauteur_debut')
}),
('Analyse et Datation', {
'fields': ('analyse', 'inedit', 'ref_biblio', 'ref_biblio_2', ('date_chrono_debut', 'date_chrono_fin'), ('citeantique', 'provinceantique'))
})
)
list_filter = ('users__nom',)
search_fields = (
'id',
'titre',
'prov_pays__nom',
'prov_region__nom',
'prov_departement__nom',
'prov_ville__nom',
'cons_pays__nom',
'cons_region__nom',
'cons_departement__nom',
'cons_ville__nom',
'cons_depot',
'materiau__nom',
'provinceantique__nom',
'siteantique__nom',
'citeantique__nom'
)
autocomplete_fields = ('prov_pays', 'prov_region', 'prov_departement','prov_ville', 'cons_pays', 'cons_region', 'cons_departement', 'cons_ville', 'materiau', 'ensemble', 'provinceantique', 'citeantique', 'monument', 'cons_depot')
inlines = [OrnementInline, MoulureInline, ComposanteInline, IllusInline]
pnt = Point(5.855572,47.019214, srid=4326)
pnt.transform(900913)
default_lon, default_lat = pnt.coords
extra = 0
Here's what the admin looks like:
The TinyMCE editor should show up after "Résumé". The dimensions are actually good, according the settings, but the interface doesn't show up. I guess it can't find the static files but can't figure out what's wrong with my paths setup.
Thanks for your help!

New model objects disappear after five minutes in Django

whenever I create a new object in one of my models, they exist for around five minutes and then disappear. I checked in both my admin view and the queryset in the shell and they just disappear. I don't understand what's happening so if anyone has any idea, that'd be very useful.
These are the models:
class Character(models.Model):
image = models.ImageField()
name = models.CharField(max_length=100)
age = models.IntegerField()
story = models.CharField(max_length=500)
def __str__(self):
return self.name
class Movie(models.Model):
image = models.ImageField()
title = models.CharField(max_length=100)
creation_date = models.DateField(auto_now=True)
rating = models.IntegerField()
characters = models.ManyToManyField(Character, blank=True, related_name='movies')
def __str__(self):
return self.title
These are the views:
class CharacterCreateAPI(generics.CreateAPIView):
queryset = Character.objects.all()
serializer_class = CharacterSerializer
permission_classes = (AllowAny,)
class MovieCreateAPI(generics.CreateAPIView):
queryset = Movie.objects.all()
serializer_class = MovieSerializer
permission_classes = (AllowAny,)
These are the serializers:
class CharacterSerializer(serializers.ModelSerializer):
movies = serializers.PrimaryKeyRelatedField(queryset=Movie.objects.all())
class Meta:
model = Character
fields = ['name', 'age', 'image', 'movies', 'story']
extra_kwargs = {'image': {'required': False, 'allow_null': True}}
class MovieSerializer(serializers.ModelSerializer):
class Meta:
model = Movie
fields = ('title', 'image', 'rating', 'characters')
extra_kwargs = {'image': {'required': False, 'allow_null': True}}
def create(self, validated_data):
characters = validated_data.pop('characters')
movie = Movie.objects.create(**validated_data)
if characters:
movie.set(characters)
movie.save()
return movie
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/3.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = ''
# 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',
'rest_framework',
'rest_auth',
'django.contrib.sites',
'allauth',
'allauth.account',
'rest_auth.registration',
'rest_framework.authtoken',
'core'
]
SITE_ID = 1
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 = 'mysite.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 = 'mysite.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/3.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/3.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/
STATIC_URL = '/static/'
# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticated',
'rest_framework.permissions.IsAdminUser',
'rest_framework.permissions.AllowAny',
],
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication',
)
}

In django admin database I am not getting expected view

In django admin database I am not getting expected view. I am following the tutorials to make a quiz app in Django. I did exactly as shown in video but still I am not getting same output. I have attached the picture of expected view and picture of what I am getting.
Getting This:
Expecting This:
models.py (in quiz):
from django.db import models
from django.contrib.auth import get_user_model
User = get_user_model()
# Create your models here.
class Quiz(models.Model):
name = models.CharField(max_length=255)
description = models.CharField(max_length=70)
slug = models.SlugField(blank=True)
roll_out = models.BooleanField(default=False)
timestamp = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ['timestamp',]
verbose_name_plural = 'Quizzes'
def __str__(self):
return self.name
class Question(models.Model):
quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE, related_name='questions')
label = models.CharField('Question', max_length=255)
order = models.IntegerField(default=0)
def __str__(self):
return self.label
class Answer(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name='answers')
label = models.CharField('Answer', max_length=255)
is_correct = models.BooleanField('Correct answer', default=False)
def __str__(self):
return self.label
class QuizTaker(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE)
score = models.IntegerField(default=0)
completed = models.BooleanField(default=False)
date_finished = models.DateTimeField()
timestamp = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.user.username
class UserAnswer(models.Model):
quiz_taker = models.ForeignKey(QuizTaker,on_delete=models.CASCADE)
quistion = models.ForeignKey(Question,on_delete=models.CASCADE)
answer = models.ForeignKey(Answer,on_delete=models.CASCADE)
def __str__(self):
return self.question.label
In admin.py
from django.contrib import admin
import nested_admin
from .models import Quiz, Question, Answer, QuizTaker, UserAnswer
# Register your models here.
class AnswerInline(nested_admin.NestedTabularInline):
model = Answer
extra = 4
max_num = 4
class QuestionInline(nested_admin.NestedTabularInline):
model = Question
inline = [AnswerInline]
extra = 5
class QuizAdmin(nested_admin.NestedModelAdmin):
inline = [QuestionInline,]
class UserAnswerInline(admin.TabularInline):
model = UserAnswer
class QuizTakerAdmin(admin.ModelAdmin):
inline = [UserAnswerInline,]
admin.site.register(Quiz,QuizAdmin)
admin.site.register(Question)
admin.site.register(Answer)
admin.site.register(QuizTaker,QuizTakerAdmin)
admin.site.register(UserAnswer)
In settings.py
"""
Django settings for assignment2 project.
Generated by 'django-admin startproject' using Django 2.1.1.
For more information on this file, see
https://docs.djangoproject.com/en/2.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.1/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATE_DIR = os.path.join(BASE_DIR,'templates')
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'u1e72cel3t20c3m5wvetnl*7w6x8srf4f#ncx6x=7*0k-w^#%x'
# 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',
'django.contrib.humanize',
'bootstrap4',
'accounts.apps.AccountsConfig',
'quiz',
'nested_admin',
]
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 = 'assignment2.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [TEMPLATE_DIR],
'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 = 'assignment2.wsgi.application'
ASGI_APPLICATION = 'assignment.routing.application'
# Database
# https://docs.djangoproject.com/en/2.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/2.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/2.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.1/howto/static-files/
LOGIN_REDIRECT_URL = 'test'
LOGOUT_REDIRECT_URL = 'thanks'
STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR,'static')]
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'static')
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/

Django 2.2:App registry error in django.Tried every solution available but none of the methods worked available on the internet

django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.
checked all INSTALLED_APPS in settings.py
registered models,apps.py.
Earlier this error was not coming when i was working with core and users applications under the same project.
settings.py
"""
Django settings for jam project.
Generated by 'django-admin startproject' using Django 2.2.1.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'bj))qqcyggizpqmxp9zru$pb%m#bt0--_z%$#z6!xz^$ij3#^#'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
#All applications are working
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'home.apps.HomeConfig',
'core.apps.CoreConfig',
'users.apps.UsersConfig',
'crispy_forms',
]
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 = 'jam.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(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 = 'jam.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/2.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/2.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/
from home import views
STATIC_URL = '/static/'
LOGIN_REDIRECT_URL = views.index
CRISPY_TEMPLATE_PACK= 'bootstrap4'
#managing media
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
home/models.py
from django.db import models
class OurPicks(models.Model):
title = models.CharField(max_length=150)
pro_id = models.AutoField
pro_desc = models.TextField()
size = models.CharField(max_length=200)
quantity = models.CharField(max_length=200)
slug = models.SlugField()
sleeves_length = models.CharField(max_length=15)
neck_style = models.CharField(max_length=20)
updated = models.DateTimeField(auto_now=True)
availability = models.BooleanField(default=True)
orignal_price = models.FloatField(blank=True)
discounted_price = models.FloatField(blank=True)
image1 = models.ImageField(upload_to='media', default='')
image2 = models.ImageField(upload_to='media', default='')
image3 = models.ImageField(upload_to='media', default='')
image4 = models.ImageField(upload_to='media', default='')
color = models.CharField(max_length=200)
JEWELLERY = 'JEWELLERY'
KURTIS = 'KURTIS'
LADIES_SUIT = 'LADIES_SUIT'
CATEGORIES = [
(JEWELLERY, 'jewellery'),
(KURTIS, 'kurtis'),
(LADIES_SUIT, 'ladies_suit'),
]
categories = models.CharField(
max_length=11,
choices=CATEGORIES,
default=None,
)
def __str__(self):
return self.title
home/admin.py
from django.contrib import admin
from .models import OurPicks
from core.apps import CoreConfig,AppConfig
from core.models import Orders
# from .modelv1 import Productcolor
#class PicksAdmin(admin.ModelAdmin):
admin.site.register(OurPicks)
home/apps.py
from django.apps import AppConfig
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.

Django admin failing to login after upgrade to 2.1

After upgrading an old Django 1.8 to 2.1, when I try to login on my admin site, I get a 404 with message:
Using the URLconf defined in <mysite>.urls, Django tried these URL patterns, in this order:
[...]
The current path, login/, didn't match any of these.
Which I guess is true because it should be on __admin/login as in my urls.py I have:
urlpatterns = [
...
path(r'__admin/', admin.site.urls),
...
]
But:
The GET request /__admin/login returns the login page as expected
The problem happens only in production (with passenger WSGI on a VPS), not on localhost
Logging in the user manually via manage.py shell and django.contrib.auth.authenticate() works correctly
Unfortunately the upgrade happened at the same time as a migration in VPS machine so there may also be a problem with the database.
Python version (on VPS): 3.6.7
Django version (on VPS): 2.1.3 (also tried with 2.1.4)
EDIT 1
I've commented out all other urls, so that now the only URL available is __admin. Now, when I login I get this error:
Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order:
1. __admin/
The current path, login/, didn't match any of these.
It looks like django is looking for login/ rather than __admin/login. Is that possible and what could be causing this?
EDIT 2
Added settings file.
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
from django.contrib import messages
PROJ_SHORTNAME = '<removed>'
PROJ_NAME = '<removed>'
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = <removed>
# 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',
'django.contrib.sites',
'bootstrap3',
'mysite',
'blog',
'envelope', # required for contact page
'crispy_forms', # required for contact page
'honeypot', # required for contact page
'braces', # required for contact page
'disqus',
'markdownx',
)
MIDDLEWARE = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
# 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware',
)
ROOT_URLCONF = '<removed>.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.template.context_processors.media',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'mysite.context_preprocessors.proj_name',
],
},
},
]
WSGI_APPLICATION = '<removed>.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': PROJ_SHORTNAME,
'HOST': 'localhost',
'USER': '<removed>',
'PASSWORD': '<removed>',
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.8/topics/i18n/
LANGUAGE_CODE = 'en-gb'
TIME_ZONE = 'Europe/London'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.8/howto/static-files/
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
MEDIA_URL = '/media/'
## Markdown
MARKDOWN_EXTENSIONS = ['extra', 'codehilite']
MESSAGE_TAGS = {
messages.DEBUG: 'debug',
messages.INFO: 'info',
messages.SUCCESS: 'success',
messages.WARNING: 'warning',
messages.ERROR: 'danger' # 'error' by default
}
## contact (envelope)
HONEYPOT_FIELD_NAME = 'email2'
CRISPY_TEMPLATE_PACK = 'bootstrap3'
ENVELOPE_USE_HTML_EMAIL = False
ENVELOPE_SUBJECT_INTRO = "[<removed>] "
ENVELOPE_EMAIL_RECIPIENTS = ['<removed>']
## disqus
DISQUS_API_KEY = '<removed>'
DISQUS_WEBSITE_SHORTNAME = '<removed>'
## django sites
SITE_ID = 1
BOOTSTRAP3 = {
# The URL to the jQuery JavaScript file
'jquery_url': STATIC_URL+'mysite/js/jquery.min.js',
# The Bootstrap base URL
'base_url': STATIC_URL+'mysite/',
# The complete URL to the Bootstrap CSS file (None means derive it from base_url)
"css_url": {
"url": "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css",
"integrity": "sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u",
"crossorigin": "anonymous",
},
# The complete URL to the Bootstrap CSS file (None means no theme)
'theme_url': None,
# The complete URL to the Bootstrap JavaScript file (None means derive it from base_url)
"javascript_url": {
"url": "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js",
"integrity": "sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa",
"crossorigin": "anonymous",
},
# Put JavaScript in the HEAD section of the HTML document (only relevant if you use bootstrap3.html)
'javascript_in_head': False,
# Include jQuery with Bootstrap JavaScript (affects django-bootstrap3 template tags)
'include_jquery': False,
# Label class to use in horizontal forms
'horizontal_label_class': 'col-md-3',
# Field class to use in horizontal forms
'horizontal_field_class': 'col-md-9',
# Set HTML required attribute on required fields
'set_required': True,
# Set HTML disabled attribute on disabled fields
'set_disabled': False,
# Set placeholder attributes to label if no placeholder is provided
'set_placeholder': True,
# Class to indicate required (better to set this in your Django form)
'required_css_class': '',
# Class to indicate error (better to set this in your Django form)
'error_css_class': 'has-error',
# Class to indicate success, meaning the field has valid input (better to set this in your Django form)
'success_css_class': 'has-success',
# Renderers (only set these if you have studied the source and understand the inner workings)
'formset_renderers':{
'default': 'bootstrap3.renderers.FormsetRenderer',
},
'form_renderers': {
'default': 'bootstrap3.renderers.FormRenderer',
},
'field_renderers': {
'default': 'bootstrap3.renderers.FieldRenderer',
'inline': 'bootstrap3.renderers.InlineFieldRenderer',
},
}
try:
from <removed>.local_settings import *
except ImportError:
pass
And the local_settings.py:
import os
DEBUG = False
STATIC_ROOT = '/home/<removed>/public_html/<removed>/static/'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': '<removed>',
'HOST': 'localhost',
'USER': '<removed>',
'PASSWORD': '<removed>',
}
}
FROM_EMAIL = '<removed>'
BOOTSTRAP3 = {
# The URL to the jQuery JavaScript file
'jquery_url': '//code.jquery.com/jquery.min.js',
}
ALLOWED_HOSTS = [
'<removed>', # Allow domain and subdomains
'.<removed>.', # Also allow FQDN and subdomains
'<removed>', # Also allow FQDN and subdomains
]
LOGIN_URL="/__admin/login/"
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'file': {
'level': 'DEBUG',
'class': 'logging.FileHandler',
'filename': os.path.expanduser('~/logs/django/debug.log'),
},
},
'loggers': {
'django': {
'handlers': ['file'],
'level': 'DEBUG',
'propagate': True,
},
},
}
TEST
I tried to reproduce your error creating an empty Django 2.1 project and then I modified projects file as you reported:
urls.py
from django.contrib import admin
from django.urls import path
urlpatterns = [path(r'__admin/', admin.site.urls)]
local_settings.py
DEBUG = False
ALLOWED_HOSTS = ['*']
LOGIN_URL = "/__admin/login/"
settings.py
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SECRET_KEY = 'secret-key'
DEBUG = True
ALLOWED_HOSTS = []
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
)
MIDDLEWARE = (
'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',
'django.middleware.security.SecurityMiddleware',
)
ROOT_URLCONF = 'so.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.template.context_processors.media',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'so.wsgi.application'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
MEDIA_URL = '/media/'
SITE_ID = 1
try:
from so.local_settings import * # noqa
except ImportError:
pass
I was not able to reproduce your error and I think your code is ok.
Suggestion
I think the main motivations for your error on the VPS is on the VPS.
Do you have any stale .pyc or .pyo files on your VPS ?
If so, try deleting them and then restarting the VPS.
If you solve your error, in order to prevent this issue in future, you should remove .pyc or .pyo files before starting your VPS.
It appears that this issue has to do with settings.py. I was facing the same issue and made changes to my settings.py
MIDDLEWARE_CLASSES renamed to MIDDLEWARE
commented reference to 'django.contrib.auth.middleware.SessionAuthenticationMiddleware'
and the problem disappeared
Try setting LOGIN_URL in your settings.py
LOGIN_URL = '__admin/login'
https://docs.djangoproject.com/en/2.1/ref/settings/#login-url
Default: '/accounts/login/'
The URL where requests are redirected for login, especially when using the login_required() decorator.
I just had to do an incremental upgrade too, from Django 1.8 to 2.2.
I did as previously suggested by bir singh (however was too long to post as a comment). I hope this helps someone.
I found the Django settings file
commented out the MIDDLEWARE_CLASSES for reference
added a MIDDLEWARE default section
# Django upgrade 1.11 to 2.x
# MIDDLEWARE_CLASSES = (
# 'django.contrib.sessions.middleware.SessionMiddleware',
# 'django.middleware.common.CommonMiddleware',
# 'django.middleware.csrf.CsrfViewMiddleware',
# 'django.contrib.auth.middleware.AuthenticationMiddleware',
# 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
# 'django.contrib.messages.middleware.MessageMiddleware',
# 'django.middleware.clickjacking.XFrameOptionsMiddleware',
# 'django.middleware.security.SecurityMiddleware',
# )
MIDDLEWARE = [
# The following is the list of default middleware in new Django projects.
'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',
]
started the runserver and checked the website functionality (all good)
previously I would be getting this error after the upgrade:
django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues:
ERRORS:
?: (admin.E408) 'django.contrib.auth.middleware.AuthenticationMiddleware' must be in MIDDLEWARE in order to use the admin application.
?: (admin.E409) 'django.contrib.messages.middleware.MessageMiddleware' must be in MIDDLEWARE in order to use the admin application.
I'm using python 3.8v and django 2.2.
I had also this problem.
using this
url(r'^$admin/', admin.site.urls) on settings.py i could not access to the login form.
However, trying this path('admin/', admin.site.urls) i was able to access and fixed it.