Error while using ckeditor with Django version 2.x - django

Please be informed I researched Stack Overflow and ckeditor documentation and configured accordingly.
First I install ckeditor using
pip install django-ckeditor
Then I configured my settings.py as below
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.1/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
# media
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
# Static files (CSS, JavaScript, Images)
STATICFILES_FINDERS = [
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
]
CKEDITOR_BASEPATH = "/static/ckeditor/ckeditor"
# CKEditor settings
CKEDITOR_UPLOAD_PATH = "uploads/"
CKEDITOR_JQUERY_URL = '//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js'
# This ensures you have all toolbar icons
CKEDITOR_CONFIGS = {
'default': {
'toolbar': None,
},
}
Then I configured my urls.py (project's url) as below
url(r'^ckeditor/', include('ckeditor_uploader.urls'))
Then I ran command collect static
ckeditor statics are collected in right location defined in settings which is /static/ckeditor/ckeditor
After that I imported and used ckeditor richtextfield in my model
from django.db import models
from ckeditor.fields import RichTextField
class Post(models.Model):
post = models.RichTextField()
While makemigrations i am getting the following error
AttributeError: module 'django.db.models' has no attribute 'RichTextField'

Change from:
post = models.RichTextField()
to:
post = RichTextField()
And in CKEDITOR_BASEPATH add "/" to the end.
CKEDITOR_BASEPATH = "/static/ckeditor/ckeditor/"

Related

Django FileSystemStorage does not save anything to media folder

I'm working on a Django backend deployed on a server, here's my settings:
DEBUG = False
STATIC_URL = "/staticfiles/"
STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles")
MEDIA_URL = "/media/"
MEDIA_ROOT = os.path.join(BASE_DIR, "media")
And I want to save the users' images outside the django folder, so I've created a custom FileSystemStorage in this way:
from django.core.files.storage import FileSystemStorage
key_store = FileSystemStorage(location="/home/usr/project/media/", base_url="/media")
Where I put the absolute path of ubuntu server.
def profile_picture_url(instance, *_):
return f"{instance.user.uuid}/profile.picture.png"
picture = models.FileField(
storage=key_store, default=None, upload_to=profile_picture_url
)
But it doesn't create any file inside media folder.
Any solution?

Django statics returns 404 error in cPanel Passenger

I used cPanel and deployed a Django application on my server using passenger_wsgi.py. The problem is when I'm trying to access static files (like admin CSS file: static/admin/css/base.css) I'm facing with 404 error.
I've already done collectstatic and added PassengerPathInfoFix method to passenger_wsgi.py file but the output log is
Not Found: /home/mysite/public_html/build/static/admin/css/base.css
even though the outputted path exists and I can edit it using vim.
My settings.py:
STATIC_ROOT = os.path.join(BASE_DIR, "static")
STATIC_URL = "/static/"
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
Any help would be appreciated.
Add this into url.py
from django.conf.urls.static import static
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Hope this help!
You can try to change STATIC_URL to STATICFILES_DIRS, this work with me!
STATICFILES_DIRS = [
BASE_DIR / 'static',
BASE_DIR / 'static/admin',
]
Thanks to Ali's answer, For anyone with the same problem, here are the steps I've done.
Wish it would be helpful:
Make sure your settings.py file contains these lines:
STATIC_ROOT = os.path.join(BASE_DIR, "static")
STATIC_URL = "/static/"
run python manage.py collectstatic
Edit your passenger_wsgi.py and add these lines:
# ...
# Import WSGI of your project
# Project Static File Path
cwd = os.getcwd()
sys.path.append(cwd)
sys.path.append(cwd + '/myapp')
SCRIPT_NAME = os.getcwd()
class PassengerPathInfoFix(object):
def __init__(self, app):
self.app = app
def __call__(self, environ, start_response):
from urllib.parse import unquote
environ['SCRIPT_NAME'] = SCRIPT_NAME
request_uri = unquote(environ['REQUEST_URI'])
script_name = unquote(environ.get('SCRIPT_NAME', ''))
offset = request_uri.startswith(script_name) and len(environ['SCRIPT_NAME']) or 0
environ['PATH_INFO'] = request_uri[offset:].split('?', 1)[0]
return self.app(environ, start_response)
application = PassengerPathInfoFix(application)
If you deployed your Django project in a subfolder inside public_html and not in the public_html directory (as mine), copy the static folder to public_html or create symbolic link using ln -s public_html/static/ public_html/subfolder/static/ (The point is the static files only load from your domain/subdomain base directory) (maybe there is a better solution but this solved my problem)
So I moved the project to the base directory of my domain and it worked.
install whitenoise and that's it !
pip install whitenoise
settings.py :
MIDDLEWARE = [
# ...
"django.middleware.security.SecurityMiddleware",
"whitenoise.middleware.WhiteNoiseMiddleware",
# ...
]

Django images not found in page view but was save after post request

I was trying to save an image but it can't be displayed through the browser. It was successfully saved in the exact location but when I pasted the link it says, "Page not found". Could someone help me with what's going on?
See output:
Browser View
Code:
Code Snippet
Settings configuration:
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
STATIC_LOCATION = "static"
MEDIA_LOCATION = "media"
settings.py
from pathlib import Path
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
urls.py
This must be applied in your settings configuration.
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
....
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Deployed Django project does not load static files

I have just deployed (first time ever) a Django project to a web server. Everything (including postgres) works flawlessly, except that static images won't load.
Here is the relevant part of the settings.py:
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, "static/")
#STATICFILES_DIRS = [
# 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'
LOGIN_REDIRECT_URL = 'home'
LOGIN_URL = 'login'
LOGOUT_URL = 'logout'
AUTH_USER_MODEL = 'account.CustomUser'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
The error message I get is the following in the console:
"GET /static/images/logo.png HTTP/1.1" 404 1808
However, when checking the file path in the console I have the following:
root#melius:/django/melius/static/images#
In this folder the files are present.
Where is my mistake?
There can be two reaon your static files not working.
First of all, Django doesn't serve static files on production.
Also i notice your static settings are wrongly configured.
Make sure your setting.py is look like this:
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'YOUR STATIC FILE FOLDERS')]
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
If you run your application on Nginx or apache2please make sure you configured the.conf` file properly to serve the static files.
Also, there is a straightforward and easy solution, that is whitenoise
If you don't want to serve your static files with Nginx or a similar server.
You can try whitenoise
To use whitenoise, please install it first and update your settings.py file like this:
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
and add this in middlware before the sessionmiddleware
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware', # Serve static in production without nginx or apache
'django.contrib.sessions.middleware.SessionMiddleware',
........
]
Hope the solution will solve your problem
Here you go for whitenoise docs: http://whitenoise.evans.io/en/stable/
Note: static root and static dirs shound't be same

django-photologue thumbnails not loading

I am trying to use django-photologue, I installed it and did mentioned settings.
I have a model Blog as follows:
class Blog(models.Model):
title = models.CharField(max_length=150)
thumbnail = models.ForeignKey(Photo, related_name='blogs')
I am able to add images to blog objects, however I do not see the thumbnail in my admin interface (clicking on it basically opens base.html stored in templates folder which I simply copied from example_project, this base.html is not important for me, however seeing this thumbnail could be interesting):
NOTE: I guess my MEDIA_ROOT and MDIA_URL properties are wrong, I am not sure what I should be writing there. I get
GET http://127.0.0.1:8000/photologue/photologue/photos/cache/dog_1_admin_thumbnail.jpg 404 (Not Found)
for
MEDIA_ROOT = os.path.join(BASE_DIR, 'photologue', )
MEDIA_URL = '/photologue/'
error, on my console.
My folder structure:
The thumbnails part of the question is fixed by doing following settings:
In my urls.py file I had to
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
#all urls
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
And in my settings.py file I added:
STATIC_ROOT = os.path.join(BASE_DIR, 'public', 'static')
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'public', 'media')
MEDIA_URL = '/media/'