I am currently learning how to use Django 3 (and Python 3.8) and I am following a tutorial to create a simple blog. I am getting a good grasp of the basic concepts so far but I am stuck at creating a migrations file.
When I enter the python manage.py makemigrations blog command into Windows Powershell, I get the error message: No installed app with label 'blog'. I have searched high and lo for an answer but I am still scratching my head. I am wondering if you lovely people would be able to offer any advice on the matter.
Here's my settings.py file:
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__)))
print("BASE_DIR = ", BASE_DIR)
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'blog',
]
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 = 'django_project.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 = 'django_project.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/'
And here's my models.pyfile of the blog app:
from django.db import models
class Author(models.Model):
name = models.CharField(max_length=100, unique=True)
email = models.EmailField(unique=True)
active = models.BooleanField(default=False)
created_on = models.DateTimeField()
last_logged_in = models.DateTimeFieldP()
class Category(models.Model):
name = model.CharField(max_length=100, unique=True)
slug = models.SlugField(max_length=100, unique=True
author = models.ForeignKey(Author, on_delete=models.CASCADE)
class Tag(model.Model):
name = models.CharField(max_length=100, unique=True)
slug = models.SlugField(max_length=100, unique=True)
author = models.ForeignKey(Author, on_delete=models.CASCADE)
class Post(models.Model):
title = models.CharField(max_length=200)
slug = models.SlugField(unique=True)
content = models.TextField()
pub_date = models.DateTimeField(auto_now_add=True)
author = models.ForeignKey(Author, on_delete=models.CASCADE)
category = models.ForeignKey(Category, on_delete=models.CASCADE)
tags = models.ManyToManyField(Tag)
I'll also post the directory to my blog app as well:
first_project
--my_venv
--django_project
----django_project
----__init__.py
----asgi.py
----settings.py
----urls.py
----wsgi.py
----blog
----migrations
----__init__.py
----templates
----__init__.py
----admin.py
----apps.py
----models.py
----tests.py
----urls.py
----views.py
----templates
----manage.py
----db.sqlite3
EDIT: Sorry about the missing blog app files, I've added the auto-generated files to the directory.
I'll also add the apps.py file, which is:
from django.apps import AppConfig
class BlogConfig(AppConfig):
name = 'blog'
As requested, this is the result of the command python manage.py showmigrations:
admin
[X] 0001_initial
[X] 0002_logentry_remove_auto_add
[X] 0003_logentry_add_action_flag_choices
auth
[X] 0001_initial
[X] 0002_alter_permission_name_max_length
[X] 0003_alter_user_email_max_length
[X] 0004_alter_user_username_opts
[X] 0005_alter_user_last_login_null
[X] 0006_require_contenttypes_0002
[X] 0007_alter_validators_add_error_messages
[X] 0008_alter_user_username_max_length
[X] 0009_alter_user_last_name_max_length
[X] 0010_alter_group_name_max_length
[X] 0011_update_proxy_permissions
contenttypes
[X] 0001_initial
[X] 0002_remove_content_type_name
sessions
[X] 0001_initial
Thank you guys for all your help. I found the solution to this problem!
It was giving me the error as explained in my original post because of anti-virus software: Comodo. Once I temporarily deactivated that software and when I corrected all the silly mistakes in my models.py folder, the makemigrations process worked and I can carry on programming.
I just want to thank you guys again for taking the time to advise me on what to do.
P.S. I just wanted to add that this Comodo antivirus software, has caused all sorts of unexplained errors during my time learning Python and then Django, which was fixed once I temporarily deactivated the software
You have not created the blog app using the django way.
You should create an app in django using the following command.
python manage.py startapp blog
It looks like you don't have all the files like suggested in comments. At least you will need to have file apps.py under your app folder, but as you have models defined and you mentions models.py and it is not listed in your file list it seems that list is not complete.
File apps.py looks like this:
from django.apps import AppConfig
class BlogConfig(AppConfig):
name = 'blog'
Please check and post your complete file list.
Please Use this command to create app in django:
python manage.py startapp your_app_name
Or:
django-admin startapp your_app_name
Related
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/
I am trying to store the questions tag in sqlite3 of Django but whenever I am trying to click on Question in /admin/ it shows error :
error image
in case image is not displayed, this is error
{
OperationalError at /admin/userinfo/question/
no such table: userinfo_question
Request Method: GET
Request URL: http://127.0.0.1:8000/admin/userinfo/question/
Django Version: 3.0.5
Exception Type: OperationalError
Exception Value:
no such table: userinfo_question
}
I have already tried
changing sqlite3 path in settings (error not resolved same error)
python manage.py migrate --run-syncdb (after applying makemigrations)(migrations apply error not resolved)
this was written while doing migrations
Creating tables...
Running deferred SQL...
so I am thinking that the table is creating but not displaying( might be)
this is my models.py
'''
from django.db import models
# Create your models here.
class Question(models.Model):
prob_link = models.CharField(max_length=500, default='')
prob_level = models.CharField(max_length=1)
prob_rating = models.IntegerField()
expression_parsing = models.BooleanField(default=False)
fft = models.BooleanField(default=False)
two_pointers = models.BooleanField(default=False)
binary_search = models.BooleanField(default=False)
dsu = models.BooleanField(default=False)
strings = models.BooleanField(default=False)
number_theory = models.BooleanField(default=False)
data_structures = models.BooleanField(default=False)
hashing = models.BooleanField(default=False)
shortest_paths = models.BooleanField(default=False)
matrices = models.BooleanField(default=False)
string_suffix_structures = models.BooleanField(default=False)
graph_matchings = models.BooleanField(default=False)
dp = models.BooleanField(default=False)
dfs_and_similar = models.BooleanField(default=False)
meet_in_the_middle = models.BooleanField(default=False)
games = models.BooleanField(default=False)
schedules = models.BooleanField(default=False)
constructive_algorithms = models.BooleanField(default=False)
greedy = models.BooleanField(default=False)
bitmasks = models.BooleanField(default=False)
divide_and_conquer = models.BooleanField(default=False)
flows = models.BooleanField(default=False)
geometry = models.BooleanField(default=False)
math = models.BooleanField(default=False)
sortings = models.BooleanField(default=False)
ternary_search = models.BooleanField(default=False)
combinatorics = models.BooleanField(default=False)
brute_force = models.BooleanField(default=False)
implementation = models.BooleanField(default=False)
sat_2 = models.BooleanField(default=False)
trees = models.BooleanField(default=False)
probabilities = models.BooleanField(default=False)
graphs = models.BooleanField(default=False)
chinese_remainder_theorem = models.BooleanField(default=False)
interactive = models.BooleanField(default=False)
other_tag = models.BooleanField(default=False)
special_problem = models.BooleanField(default=False)
'''
here is settings.py
"""
Django settings for codeforces_crawler project.
Generated by 'django-admin startproject' using Django 3.0.2.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/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/3.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'sp_$b%e_g1v)eam^rqlef5v8##&6qhxw1&2f6me^c!b^v+rkwl'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'userinfo.apps.UserinfoConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
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 = 'codeforces_crawler.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 = 'codeforces_crawler.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/'
this is views.py
from django.shortcuts import render
from .scraping import scrape
def index(request):
return render(request, 'userinfo/index.html')
def detail(request):
user = request.POST['user'] # user is the name of the input
# rank,color,ar,institute,ac,wa,tle,rte,mle,challenged,cpe,skipped,ile,other = scrape(user)
verdict = scrape(user)
if verdict == False:
exists = verdict
return render(request, 'userinfo/detail.html', {'exists': exists})
else:
exists = verdict[0]
rank = verdict[1]
color = verdict[2]
ar = verdict[3]
institute = verdict[4]
ac = verdict[5]
wa = verdict[6]
tle = verdict[7]
rte = verdict[8]
mle = verdict[9]
challenged = verdict[10]
cpe = verdict[11]
skipped = verdict[12]
ile = verdict[13]
other = verdict[14]
rating = verdict[15]
return render(request, 'userinfo/detail.html',
{'exists': exists, 'user': user, 'rank': rank, 'color': color, 'ar': ar, 'institute': institute,
'ac': ac, 'wa': wa, 'tle': tle, 'rte': rte, 'mle': mle, 'challenged': challenged
, 'cpe': cpe, 'skipped': skipped, 'ile': ile, 'other': other, 'rating': rating})
# return render(request, 'userinfo/detail.html', {'user': user, 'verdict':verdict,})
this is admin.py
'''
from django.contrib import admin
from .models import Question
# Register your models here.
admin.site.register(Question)
'''
this is url.py
from django.urls import path
from . import views
app_name = 'userinfo'
urlpatterns = [
path('',views.index, name='index'),
path('detail/',views.detail,name='detail'),
]
or if there is any other method to see what questions had been added in my database.
Not able to resolve this error for the last 3 days.Thanks in advance for your help.
The error message "no such table: userinfo_question" indicates that Django has not turned your model representation into tables within your database.
Check that your app userinfo is listed under INSTALLED_APPS in settings.py.
You should also run makemigrations before running migrate
python manage.py makemigrations
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.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.
When I run python populate_rango.py it gives this
Starting Rango population script...
- Python - Page object
- Python - Page object
- Python - Page object
- Django - Page object
- Django - Page object
- Django - Page object
- Other Frameworks - Page object
- Other Frameworks - Page object
Why it does not read the titles correctly like this?
Starting Rango population script...
- Python - Official Python Tutorial
- Python - How to Think like a Computer Scientist
- Python - Learn Python in 10 Minutes
- Django - Official Django Tutorial
- Django - Django Rocks
- Django - How to Tango with Django
- Other Frameworks - Bottle
- Other Frameworks - Flask
So it does not work. my populate_rango.py is:
import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'sarpedon33.settings')
import django
django.setup()
from rango.models import Category, Page
def populate():
python_cat = add_cat('Python')
add_page(cat=python_cat,
title="Official Python Tutorial",
url="http://docs.python.org/2/tutorial/")
add_page(cat=python_cat,
title="How to Think like a Computer Scientist",
url="http://www.greenteapress.com/thinkpython/")
add_page(cat=python_cat,
title="Learn Python in 10 Minutes",
url="http://www.korokithakis.net/tutorials/python/")
django_cat = add_cat("Django")
add_page(cat=django_cat,
title="Official Django Tutorial",
url="https://docs.djangoproject.com/en/1.5/intro/tutorial01/")
add_page(cat=django_cat,
title="Django Rocks",
url="http://www.djangorocks.com/")
add_page(cat=django_cat,
title="How to Tango with Django",
url="http://www.tangowithdjango.com/")
frame_cat = add_cat("Other Frameworks")
add_page(cat=frame_cat,
title="Bottle",
url="http://bottlepy.org/docs/dev/")
add_page(cat=frame_cat,
title="Flask",
url="http://flask.pocoo.org")
# Print out what we have added to the user.
for c in Category.objects.all():
for p in Page.objects.filter(category=c):
print "- {0} - {1}".format(str(c), str(p))
def add_page(cat, title, url, views=0):
p = Page.objects.get_or_create(category=cat, title=title)[0]
p.url=url
p.views=views
p.save()
return p
def add_cat(name):
c = Category.objects.get_or_create(name=name)[0]
return c
# Start execution here!
if __name__ == '__main__':
print "Starting Rango population script..."
populate()
my project folder name is sarpedon33 that is why it is like that.
Models:
from django.db import models
# Create your models here.
class Category(models.Model):
name = models.CharField(max_length=128, unique=True)
def __unicode__(self): #For Python 2, use __str__ on Python 3
return self.name
class Page(models.Model):
category = models.ForeignKey(Category)
title = models.CharField(max_length=128)
url = models.URLField()
views = models.IntegerField(default=0)
def __unicode__(self):
return self.name
class Ox(models.Model):
horn_length = models.IntegerField()
class Meta:
ordering = ["horn_length"]
verbose_name_plural = "categories"
def __unicode__(self): #For Python 2, use __str__ on Python 3
return self.title
Ok I have added Page Model however this time I get AttributeError: 'Page' object has no attribute 'name'.
Here is my settings.py :
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATIC_PATH = os.path.join(BASE_DIR,'static')
STATIC_URL = '/static/' # You may find this is already defined as such.
STATICFILES_DIRS = (STATIC_PATH,)
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media') # Absolute path to the media directory
# 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 = '&9(_icx1*u8l0ulfa_vx1d0=oq9%*1jjw-1zl3t8b20_)5-nny'
# 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',
'rango'
)
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 = 'sarpedon33.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 = 'sarpedon33.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.8/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/1.8/howto/static-files/
STATIC_URL = '/static/'
Your models most likely lack the
def __unicode__(self):
return self.name
functions. When printing it calls these functions, which you override in the models. Refer to 5.3. Creating Models in http://www.tangowithdjango.com/book/chapters/models.html.
As the error message says, the Page model does not have an attribute called name, but you are trying to access it in the __unicode__ method. Change the method definition like this:
def __unicode__(self):
return self.title