Django ckeditor can not add youtube plugin - python

I have seen this tutorial https://samulinatri.com/blog/django-ckeditor-codesnippet-hightlightjs-youtube/ and I have downloaded the youtube plugin here https://ckeditor.com/cke4/addon/youtube
Then I created the youtube folder and pushed it into it. Specifically my_project / static / ckeditor / ckeditor / plugins / youtube /
After I python manage.py runserver, field ['content'] show normal, field ['content1'] it doesn't work (does not display frames textarea).
Someone helped me check, I did something wrong. Thanks !!!
File model.py
class Posts(models.Model):
title = models.CharField(max_length=50)
content = RichTextUploadingField(extra_plugins=['codesnippet'],)
content1 = RichTextUploadingField(
config_name='special',
extra_plugins=['youtube'],
external_plugin_resources=[(
'youtube',
'/static/ckeditor/ckeditor/plugins/youtube/youtube/',
'plugin.js',
)],
)
File setting.py
INSTALLED_APPS = [
'suit',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
'ckeditor',
'ckeditor_uploader',
]
CKEDITOR_UPLOAD_PATH = "uploads/"
CKEDITOR_CONFIGS = {
'default': {
'toolbar': 'full',
},
'special': {
'toolbar': 'Special',
'toolbar_Special': [
['Bold'], ['CodeSnippet', 'Youtube'],
],
'extraPlugins': ','.join(['codesnippet', 'youtube']),
}
}
File urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('account/', include(('accounts.urls', 'accounts'), namespace='accounts')),
path('blog/', include(('blog.urls', 'blog'), namespace='blog')),
path('ckeditor/', include('ckeditor_uploader.urls')),
]
if settings.DEBUG:
import debug_toolbar
debug_patterns = [
re_path(r'^__debug__/', include(debug_toolbar.urls)),
]
urlpatterns = debug_patterns + urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
My_project
├── blog <= This my_app
│ ├── view.py
│ ├── form.py
│ ├── model.py
├── project <= Project settings directory
│ ├── __init__.py
│ ├── settings.py <= settings
│ ├── urls.py
│ └── wsgi.py
├── static
│ ├── ckeditor
│ ├── ckeditor_uploader
│ ├── ckeditor
│ ├── plugins
│ └── youtube
│ └── youtube
│ └── images
│ └── lang
│ └── plugin.js
│ └── ....
│ └── ...
│ └── ...

In your models.py file, you need to point to the directory where the plugin.js is.
I believe the directory you should refer to is this:
class Posts(models.Model):
title = models.CharField(max_length=50)
content = RichTextUploadingField(extra_plugins=['codesnippet'],)
content1 = RichTextUploadingField(
config_name='special',
extra_plugins=['youtube'],
external_plugin_resources=[(
'youtube',
'/static/ckeditor/ckeditor/plugins/youtube/',
'plugin.js',
)],
)

Related

How do I set up my Django urlpatterns within my app (not project)

Let's say I've got the classic "School" app within my Django project. My school/models.py contains models for both student and course. All my project files live within a directory I named config.
How do I write an include statement(s) within config/urls.py that references two separate endpoints within school/urls.py? And then what do I put in schools/urls.py?
For example, if I were trying to define an endpoint just for students, in config/urls.py I would do something like this:
from django.urls import path, include
urlpatterns = [
...
path("students/", include("school.urls"), name="students"),
...
]
And then in school/urls.py I would do something like this:
from django.urls import path
from peakbagger.views import StudentCreateView, StudentDetailView, StudentListView, StudentUpdateView, StudentDeleteView
urlpatterns = [
# ...
path("", StudentListView.as_view(), name="student-list"),
path("add/", StudentCreateView.as_view(), name="student-add"),
path("<int:pk>/", StudentDetailView.as_view(), name="student-detail"),
path("<int:pk>/update/", StudentUpdateView.as_view(), name="student-update"),
path("<int:pk>/delete/", StudentDeleteView.as_view(), name="student-delete"),
]
But how do I do I add another urlpattern to config/urls.py along the lines of something like this? The include statement needs some additional info/parameters, no?
from django.urls import path, include
urlpatterns = [
...
path("students/", include("school.urls"), name="students"),
path("courses/", include("school.urls"), name="courses"),
...
]
And then what happens inside of school/urls.py?
I'm open to suggestions, and definitely am a neophyte when it comes to the Django philosophy. Do I need an additional urls.py somewhere? I'd prefer not to put everything in config/urls.py and I'd prefer not to build a separate app for both students and courses.
I would rather create two (or more) urls.py files and then point them separately.
# directory structure
school/
├── admin.py
├── apps.py
├── __init__.py
├── migrations
│   └── __init__.py
├── models.py
├── tests.py
├── urls
│   ├── course.py
│   ├── __init__.py
│   └── student.py
└── views.py
# school/urls/course.py
from django.urls import path
from school.views import CourseListView
urlpatterns = [
path("", CourseListView.as_view(), name="course_list"),
# other URLs
]
# school/urls/student.py
from django.urls import path
from school.views import StudentListView
urlpatterns = [
path("", StudentListView.as_view(), name="student_list"),
# other URLs
]
# config/urls.py
from django.urls import include, path
urlpatterns = [
path("student/", include("school.urls.student")),
path("course/", include("school.urls.course")),
# other URLs
]
The best solution for you is to make separate urls directory inside your app
For example if you have school as app then
app
├── School
│ ├── views.py
│ └── models.py
| └── urls
| └── __init__.py
| └── urls.py
| └── school_urls.py
| └── course_urls.py
Now in your main project urls you can set this way
urlpatterns = [
...
path("", include("school.urls"), name="students"),
...
]
and in urls.py of your school urls folder you can do this way
urlpatterns = [
...
path("students/", include("school.urls.school_urls"), name="students"),
path("course/", include("school.urls.course_urls"), name="course"),
...
]
and you can do add course view in course url folder and another student view in student urls file

Error in models folder "doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS"

I can't find a solution for the following error:
RuntimeError: Model class users.models.User.User doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS.
The INSTALLED_APPS:
LOCAL_APPS = [
"api.users",
"api.achievements",
"api.others",
]
# https://docs.djangoproject.com/en/dev/ref/settings/#installed-apps
INSTALLED_APPS = DJANGO_APPS + THIRD_PARTY_APPS + LOCAL_APPS
Models folder
users/models/__init__.py:
from .User import * # noqa
from .Profile import * # noqa
users/models/User.py:
""" User related models """
from django.contrib.auth.models import AbstractUser
from django.db import models
from django.urls import reverse
from django_countries.fields import CountryField
from api.others.constants import GENDER
class User(AbstractUser):
"""
Default custom user model for Dezumi API.
If adding fields that need to be filled at user signup,
check forms.SignupForm and forms.SocialSignupForms accordingly.
"""
birth_date = models.DateField(null=True, blank=True)
country = CountryField(null=True, blank=True, blank_label='Select country')
gender = models.CharField(choices=GENDER, max_length=6, null=True, blank=True)
is_verified = models.BooleanField(
default=False,
)
def get_absolute_url(self):
"""Get url for user's detail view.
Returns:
str: URL for user detail.
"""
return reverse("users:detail", kwargs={"username": self.username})
The app is on installed_apps, so what could it be? Something with the init.py?
Directory Structure:
api
├── api
│ ├── __init__.py
│ ├── conftest.py
│ ├── users
│ │ ├── admin
│ │ ├── api
│ │ │ ├── serializers.py
│ │ │ └── views.py
│ │ ├── migrations
│ │ ├── models
│ │ │ ├── __init__.py
│ │ │ ├── Profile.py
│ │ │ └── User.py
│ │ ├── __init__.py
│ │ ├── apps.py
│ │ └── ...
│ └── ...
├── config
│ ├── settings
│ │ ├── __init__.py
│ │ ├── base.py
│ │ ├── local.py
│ │ ├── production.py
│ │ └── test.py
│ ├── __init__.py
│ └── ...
├── requirements
├── utility
├── manage.py
└── ...
Log:
File "path\api\api\users\admin\__init__.py", line 1, in <module>
from .Profile import * # noqa
File "path\api\api\users\admin\Profile.py", line 3, in <module>
from users.models.Profile import Profile
File "path\api\api\users\models\__init__.py", line 1, in <module>
from .User import * # noqa
File "path\api\api\users\models\User.py", line 11, in <module>
class User(AbstractUser):
File "path\lib\site-packages\django\db\models\base.py", line 113, in __new__
raise RuntimeError(
RuntimeError: Model class users.models.User.User doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS.
apps.py from users
from django.apps import AppConfig
from django.utils.translation import gettext_lazy as _
class UsersConfig(AppConfig):
name = "api.users"
verbose_name = _("Users")
def ready(self):
try:
import api.users.signals # noqa F401
except ImportError:
pass
Explicitly referencing the Users app configuration class might work:
LOCAL_APPS = [
"api.users.apps.UsersConfig",
...
]

Accessing Statics Files in Django

I am having a structure of Django Project as:
│ db.sqlite3
│ manage.py
│
├───static
│ │ 1.jpg
│ │ bg1.jpg
│ │
│ └───css
│ login.css
│
├───templates
│ home.html
│ login.html
│ register.html
│
├───User
│ │ admin.py
│ │ apps.py
│ │ models.py
│ │ tests.py
│ │ urls.py
│ │ views.py
│ │ __init__.py
│ │
│ ├───migrations
│ │ │ __init__.py
│ │ │
│ │ └───__pycache__
│ │ __init__.cpython-38.pyc
│ │
│ └───__pycache__
│ admin.cpython-38.pyc
│ apps.cpython-38.pyc
│ models.cpython-38.pyc
│ urls.cpython-38.pyc
│ views.cpython-38.pyc
│ __init__.cpython-38.pyc
│
└───Website
│ asgi.py
│ settings.py
│ urls.py
│ wsgi.py
│ __init__.py
│
└───__pycache__
settings.cpython-38.pyc
urls.cpython-38.pyc
wsgi.cpython-38.pyc
__init__.cpython-38.pyc
Settings.py
"""
from pathlib import Path
import os
# 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 = 'django-insecure-c*3$w_63#$^8g&_fn%r=-23n^e#nrmxzxt7eh*owsz^mlrk5dr'
# 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',
'User'
]
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 = 'Website.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 = 'Website.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/'
STATICFILES_DIR= [os.path.join(BASE_DIR,'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'
And my Register.html File
{% load static %}
<html>
<head>
<title></title>
<style>
body
{
background:url({% static 'bg1.jpg' %});
}
</style>
</head>
<body>
<img src="{% static '1.jpg' %}">
<h1> HELOO </h1>
</body>
</html>
I have loaded the static and also the path for the static files still its not able to find image which i am providing in my html page. No issues while using template folder but only for static folder my project is not able to get the images and paste it on the browser.
Changing STATICFILES_DIR to STATICFILES_DIRS in setting.py helped to fix this error.
Thanks to Afzal Saiyed

Django tamplate can not loaded

I called a template in the django render function, but django cannot find it
here is the django view code:
from django.shortcuts import render
# Create your views here.
def home_page(request):
return render(request, "index.html")
And after this I tried to check my settings.py and urls.py, but found nothing, and the file is also in the tamplate subfolder of the app
here is the directory structure:
│ .gitignore
│ db.sqlite3
│ funcational_test.py
│ manage.py
│
├─Terminal_equipment_management
│ │ asgi.py
│ │ settings.py
│ │ urls.py
│ │ view.py
│ │ wsgi.py
│ │ __init__.py
│ │
│ └─__pycache__
│
└─webui
│ admin.py
│ apps.py
│ models.py
│ tests.py
│ views.py
│ __init__.py
│
├─migrations
│
├─templates
index.html
the settings.py is:
INSTALLED_APPS = [
"api",
"webui",
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
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',
],
},
},
]
urls.py is:
from django.contrib import admin
from django.urls import path, include
from webui import views
urlpatterns = [
path("", views.home_page, name="home_page"),
]
But when I visit localhost:8000/, Django will report TemplateDoesNotExist at /
here is some Error Message:
Template-loader postmortem
Django tried loading these templates, in this order:
Using engine django:
django.template.loaders.app_directories.Loader: C:\ProgramData\Miniconda3\lib\site-packages\django\contrib\admin\templates\index.html (Source does not exist)
django.template.loaders.app_directories.Loader: C:\ProgramData\Miniconda3\lib\site-packages\django\contrib\auth\templates\index.html (Source does not exist)
When I copied the files to the above two folders, the template took effect.
I can't be sure what happened
By Google Translate
Add Template DIRS:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [BASE_DIR / "template"],
'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',
],
},
},
]
I think you forgot to put s for template folder names
└─webui
│
├─tamplates
index.html
First, tamplates should be templates. Second, django looks inside a folder under templates for the app name. It seems redundant, and I agree, but that caused me issues when I was first using django.
└─webui
│
└─templates
│
└─webui
│
└─index.html

TemplateDoesNotExist error in django with celery

I am learning to use celery with django through this tutorial. In this tutorial, the person is developing a webscraping tool with django and celery. I am trying to follow the tutorial but I am facing the following error message
TemplateDoesNotExist at /
home.html, scraping/products_list.html
this is how my files are arranged
.
├── celerybeat-schedule.db
├── celerydjangotutorial
│   ├── __init__.py
│   ├── asgi.py
│   ├── celery.py
│   ├── settings.py
│   ├── templates
│   │   ├── base.html
│   │   └── home.html
│   ├── urls.py
│   ├── views.py
│   └── wsgi.py
├── db.sqlite3
├── manage.py
└── scraping
├── __init__.py
├── admin.py
├── apps.py
├── migrations
│   ├── 0001_initial.py
│   ├── 0002_auto_20200827_0735.py
│   ├── __init__.py
│   └── __pycache__
│   ├── 0001_initial.cpython-38.pyc
│   ├── 0002_auto_20200827_0735.cpython-38.pyc
│   └── __init__.cpython-38.pyc
├── models.py
├── tasks.py
├── tests.py
└── views.py
where celerydjangotutorial is the django project and scraping is a django application. In the tutorial, the person places the templates into the project directory. he also creates a views file in the project directory. I followed him as he does in the tutorial. here is my code.
celerydjangotutorial/urls.py
from django.contrib import admin
from django.urls import path, include
from .views import HomePageView
urlpatterns = [
path('', HomePageView.as_view(), name='home'),
path('admin/', admin.site.urls),
]
celerydjangotutorial/views.py
from django.shortcuts import render
from django.views import generic
from scraping.models import Products
class HomePageView(generic.ListView):
template_name = 'home.html'
context_object_name = 'products'
def get_queryset(self):
return Products.objects.all()
scraping/models.py
from django.db import models
class Products(models.Model):
title = models.CharField(max_length=200)
link = models.CharField(max_length=2083, default="", unique=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
website = models.CharField(max_length=30, default="", blank=True, null=True)
scraping/tasks.py
import time
import json
from datetime import datetime
from celery import Celery
from celery.schedules import crontab
from celery import shared_task
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.common.exceptions import TimeoutException, NoSuchElementException
from selenium.webdriver.common.keys import Keys
#shared_task
def scrape():
try:
print('starting the scraping process')
product_list = []
url = f'https://www.amazon.com/s?k=chips&ref=nb_sb_noss_2'
driver = webdriver.Chrome('./chromedriver')
driver.get(url)
driver.implicitly_wait(15)
links = driver.find_elements_by_class_name("a-size-mini")
for link in links:
element = WebDriverWait(driver, 5).until(
EC.presence_of_element_located((By.LINK_TEXT, link.text)))
product_meta = {
'link': element.get_attribute('href'),
'website': 'amazon'
}
product_list.append(product_meta)
print('scraping process completed')
return save_function(product_list)
except Exception as e:
print('scraping failed')
print(e)
#shared_task(serializer='json')
def save_function(product_list):
print('saving extracted data')
new_count = 0
for product in product_list:
try:
Products.objects.create(
title = product['title'],
link = product['link'],
website = product['website']
)
new_count += 1
except Exception as e:
print('failed at latest_product is None')
print(e)
break
return print('finished')
celerydjangotutorial/celery.py
from __future__ import absolute_import
import os
from celery import Celery
from celery.schedules import crontab
os.environ.setdefault('DJANGO_SETTINGS_MODULE','celerydjangotutorial.settings')
app = Celery('celerydjangotutorial')
app.conf.timezone = 'UTC'
app.config_from_object("django.conf:settings", namespace="CELERY")
app.autodiscover_tasks()
settings.py
...
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'scraping.apps.ScrapingConfig'
]
...
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ['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',
],
},
},
]
...
CELERY_BROKER_URL = 'amqp://localhost:5672'
CELERY_RESULT_BACKEND = 'amqp://localhost:5672'
CELERY_ACCEPT_CONTENT = ['application/json']
CELERY_TASK_SERIALIZER = 'json'
CELERY_RESULT_SERIALIZER = 'json'
CELERY_TIMEZONE = 'UTC'
I am not sure what I am doing wrong. I followed most of the tutorial. Except for tasks.py the rest of the code is similar to his code. Please help me.
Thanks in advance
[EDIT-1] posting the entire error
Internal Server Error: /
Traceback (most recent call last):
File "/Users/sashaanksekar/anaconda3/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/Users/sashaanksekar/anaconda3/lib/python3.8/site-packages/django/core/handlers/base.py", line 145, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/Users/sashaanksekar/anaconda3/lib/python3.8/site-packages/django/core/handlers/base.py", line 143, in _get_response
response = response.render()
File "/Users/sashaanksekar/anaconda3/lib/python3.8/site-packages/django/template/response.py", line 105, in render
self.content = self.rendered_content
File "/Users/sashaanksekar/anaconda3/lib/python3.8/site-packages/django/template/response.py", line 81, in rendered_content
template = self.resolve_template(self.template_name)
File "/Users/sashaanksekar/anaconda3/lib/python3.8/site-packages/django/template/response.py", line 63, in resolve_template
return select_template(template, using=self.using)
File "/Users/sashaanksekar/anaconda3/lib/python3.8/site-packages/django/template/loader.py", line 47, in select_template
raise TemplateDoesNotExist(', '.join(template_name_list), chain=chain)
django.template.exceptions.TemplateDoesNotExist: home.html, scraping/products_list.html
Try adding app name under templates folder and move HTML files into it.
So it should be like
templates/celerydjangotutorial/
base.html
home.html
Check the names of files, folders and path

Categories

Resources