Integrate TinyMCE to django - django

Unlike most articles , i am not trying to integrate the tinyMCE into the admin page.
I'm building a site with multiple blog's and i want to integrate tinyMCE into a textarea where the user is supposed to enter his article. The above mentioned textarea is not in the admin console.
I read the docs and followed the steps line by line. The only change that i made was instead of MEDIA_ROOT i used STATIC_ROOT.
My Setting.py
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'tinymce',
'pages',
'blog',
'django_summernote',
)
MIDDLEWARE_CLASSES = (
'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',
)
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
TEMPLATE_CONTEXT_PROCESSORS = {
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'django.core.context_processors.request',
}
STATIC_ROOT = 'F:/Projects/trebuchet/site/blog_test/'
STATIC_URL = '/static/'
############ TINY MCE ################
TINYMCE_JS_URL = os.path.join(STATIC_ROOT, "static/tiny_mce/tiny_mce.js")
TINYMCE_JS_ROOT = os.path.join(STATIC_ROOT, "static/tiny_mce")
TINYMCE_JS_URL = os.path.join(STATIC_ROOT,'static/tiny_mce/tiny_mce_src.js')
TINYMCE_DEFAULT_CONFIG = {
"relative_urls": "false",
"theme": "advanced",
"theme_advanced_buttons1": "formatselect,bold,italic,underline,link,unlink,bullist,undo,code,image",
"theme_advanced_buttons2": "",
"theme_advanced_buttons3": "",
"plugins": "paste",
"height": "550px",
"width": "750px",
}
TINYMCE_SPELLCHECKER = True
TINYMCE_COMPRESSOR = True
BlogForm.py
class addBlog(forms.ModelForm):
body = forms.CharField(widget=TinyMCE(attrs={'cols': 80, 'rows': 30}))
class Meta:
model = ArticleModel
fields = ['title', 'body', 'category']
widgets = {'body': TinyMCE(attrs={'cols': 80, 'rows': 30})}
class Media:
js = ( 'static/tiny_mce/tiny_mce.js', 'static/tiny_mce/blog_textareas.js')
models.py
class Category(models.Model):
name = models.CharField(max_length=30)
description = models.TextField(max_length=100)
def __unicode__(self):
return self.name
class ArticleModel(models.Model):
title = models.CharField(max_length=200)
body = models.TextField()
datetime = models.DateTimeField()
username = models.CharField(max_length=50)
category = models.CharField(max_length=30)
tags = JSONField()
def __unicode__(self):
return self.title
Now i tried a lot of solutions, with no success.

Well, why don't you try adding ckeditor(another rich text editor) to your adminsite by using javascript version of ckeditor, for example:
Download ckeditor from http://ckeditor.com/download and extract the zip file, put the unzipped folder in static root. add ckeditor static files to your admin's template like:
In admin>base.html(template):
<script src="{{STATIC_URL}}ckeditor/ckeditor.js"></script>
From your class ArticleModel, I am assuming you want to add ckeditor to body, and in admin site, it will create a TextField with id id_body, so all you need to do is this(in admin>base.html):
<script>
CKEDITOR.replace( '#id_body' );
</script>
Ps: I am ignoring forms here.

Related

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/

TinyMCE not showing up in Django admin

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.

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.

Error in connecting django with mongodb: ImportError: No module named django.auth

I am trying to create a blog using django and mongodb in aws ec2 instance
And in the file models.py, I am making following changes
from datetime import datetime
from mongoengine import *
from mongoengine.django.auth import User
from django.core.urlresolvers import reverse
class Post(Document):
user = ReferenceField(User, reverse_delete_rule=CASCADE)
title = StringField(max_length=200, required=True)
text = StringField(required=True)
text_length = IntField()
date_modified = DateTimeField(default=datetime.now)
is_published = BooleanField()
from django.core.urlresolvers import reverse
class Post(Document):
user = ReferenceField(User, reverse_delete_rule=CASCADE)
title = StringField(max_length=200, required=True)
text = StringField(required=True)
text_length = IntField()
date_modified = DateTimeField(default=datetime.now)
is_published = BooleanField()
def __unicode__(self):
return self.title
def save(self, *args, **kwargs):
self.text_length = len(self.text)
return super(Post, self).save(*args, **kwargs)
def get_absolute_url(self):
return reverse('detail', args=[self.id])
def get_edit_url(self):
return reverse('update', args=[self.id])
def get_delete_url(self):
return reverse('delete', args=[self.id])
And, I get this error
Traceback (most recent call last):
File "models.py", line 7, in <module>
from mongoengine.django.auth import User
ImportError: No module named django.auth
And, in settings.py file, I am making following changes
import os
from mongoengine import *
PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = ['54.149.63.203', 'localhost', '127.0.0.1']
# 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',
'LJblog',
'django_extensions',
'mongoengine.django.mongo_auth',
)
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',
)
ROOT_URLCONF = 'LJ.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 = 'LJ.wsgi.application'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.dummy',
'NAME': '',
'USER': '',
'PASSWORD': '',
'HOST': '55.181.26.33', //mongodb ip address
'PORT': '27017',
}
}
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
MEDIA_ROOT = os.path.join(PROJECT_ROOT, '..', 'media')
MEDIA_URL = '/media/'
STATIC_ROOT = os.path.join(PROJECT_ROOT, '..', 'static')
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(PROJECT_ROOT, 'static'),
)
TEMPLATE = (
os.path.join(PROJECT_ROOT, 'templates'),
)
AUTHENTICATION_BACKENDS = (
'mongoengine.django.auth.MongoEngineBackend',
)
SESSION_ENGINE = 'mongoengine.django.sessions'
AUTH_USER_MODEL = 'mongo_auth.MongoUser'
MONGOENGINE_USER_DOCUMENT = 'mongoengine.django.auth.User'
MONGO_DATABASE_NAME = 'LJ_blog'
from mongoengine import connect
connect(MONGO_DATABASE_NAME)
So, how can I resolve the import error?
Django support was removed from MongoEngine in 0.10.0. You might be able to get an earlier version to work, but it might not support recent versions of Django.
With mongoengine 0.10 we can see that
/usr/lib/python2.7/site-packages/mongoengine/
will not have django package in it.
Install mongoengine 0.9 using
sudo pip install mongoengine==0.9
and the django package (support or extension) will be available.