I am trying to load my CSS, images, and javascript into my Django template using
{{ STATIC_URL }}
I am having a problem getting it to work. Here is the relevant code:
Url's.py:
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
...
urlpatterns += staticfiles_urlpatterns()
Settings.py
import os
DEBUG = True
TEMPLATE_DEBUG = DEBUG
PROJECT_ROOT = os.path.realpath(os.path.dirname(__file__))
MEDIA_URL = '/assets/'
STATIC_ROOT = os.path.realpath(os.path.join(PROJECT_ROOT, 'static'))
STATIC_URL = '/static/'
STATICFILES_DIRS = (
"/Users/Chris/project/static/",
)
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
Stylesheet URl:
<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}css/style.css">
If you need anymore information just ask, and thanks for your help!
UPDATE:
I have added the following things trying to fix the problem. But it still persists:
To the views where I'm trying to import the stylesheet:
'context_instance':RequestContext(request),
To the setting.py file:
TEMPLATE_CONTEXT_PROCESSORS = (
"django.contrib.auth.context_processors.auth",
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"django.core.context_processors.media",
"django.core.context_processors.static",
"django.contrib.messages.context_processors.messages",
)
Here is my Installed App's if this helps:
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'djblog',
)
My URLs.py file for the admin, and pointing to my other URL file:
from django.conf.urls.defaults import *
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'blog.views.home', name='home'),
# url(r'^blog/', include('blog.foo.urls')),
url(r'^admin/', include(admin.site.urls)),
(r'^', include('djblog.urls')),
)
My main URL file:
from django.conf.urls.defaults import *
from views import *
from models import *
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns = patterns('',
(r'^$', list),
(r'^archive/(?P<archive>\d{1,2})/$', list),
(r'^\d{4}/\d{1,2}/(?P<sl>.*)/$', detail),
(r'^(?P<year>\d{4})/(?P<month>\d{1,2})/$', month),
(r'^(?P<year>\d{4})/$', year),
(r'^category/$', category),
(r'^category/(?P<category>.*)/$', one_category),
(r'^tag/$', tag),
(r'^tag/(?P<tag>.*)/$', one_tag),
)
urlpatterns += staticfiles_urlpatterns()
I have solved my own question. With the help of Kay Zhu
In my views I was passing the "context_instance" keyword argument to render_to_response, wrong.
Here is an example of the correct usage of context_instance:
def one_tag(request, tag):
#http://site_name/tag/tag_name
posts = Post.objects.order_by('-published').filter(tags__name=tag.lower())
return render_to_response('blog/one_tag.html',
{'posts':posts, 'tag':tag,},
context_instance=RequestContext(request))
This might also solve your similar problem. Add a file to your program directory with the following code:
def media_url(request):
from django.conf import settings
return {'media_url': settings.MEDIA_URL}
And this blog post has a lot of good information: http://www.b-list.org/weblog/2006/jun/14/django-tips-template-context-processors/
Be wary though, its from 2006 :)
Related
This is a duplicate of Django Ckeditor image browser not finding images, but I believe the answer there is wrong (there is an obvious bug in it with an undefined variable, not to mention the lack of Python indentation).
I'm using Django CKEditor 5.0.3 and Django 1.9.6. I am able to upload images in my admin, but they appear as a red X within the admin and do not appear on my site.
I'm still struggling a bit with MEDIA_ROOT and whatnot, but I think I have it right:
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static"),
)
MEDIA_URL = "image_upload/"
MEDIA_ROOT = os.path.join(BASE_DIR, "image_upload")
CKEDITOR_UPLOAD_PATH = 'uploads/'
CKEDITOR_IMAGE_BACKEND = "pillow"
CKEDITOR_UPLOAD_SLUGIFY_FILENAME = False
My urls.py, including my attempt at cleaning up the linked answer:
from django.conf import settings
from django.conf.urls import url, include
from django.conf.urls.static import static
from django.contrib import admin
from mainsite.views import HomepageView, AboutView, ContactView
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns = [
url(r'^admin/', admin.site.urls, name="admin"),
url(r'^$', HomepageView.as_view(), name="homepage"),
url(r'^about/', AboutView.as_view(), name="about"),
url(r'^contact/', ContactView.as_view(), name="contact"),
url(r'^blog/', include("blog.urls", namespace="blog")),
url(r'^ckeditor/', include('ckeditor_uploader.urls')),
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
if settings.DEBUG:
urlpatterns += [
url(r'^media/(?P<path>.*)$',
'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT,
}
),
]
urlpatterns += staticfiles_urlpatterns()
Using CKEDITOR_UPLOAD_PATH = 'uploads/' makes django-ckeditor to upload an image to /media/uploads/, like:
settings.py:
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static/'),
]
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
MEDIA_URL = '/media/'
CKEDITOR_UPLOAD_PATH = 'uploads/'
When using the Django's dev server, static files are served by default but not media files, so you can force the server to consider them, the url configuration below should work.
urls.py:
from django.conf.urls import url, include
from django.contrib import admin
from django.conf import settings
from django.views.static import serve
from .views import HomeView
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', HomeView.as_view(), name='home'),
url(r'^ckeditor/', include('ckeditor_uploader.urls')),
# serving media files only on debug mode
if settings.DEBUG:
urlpatterns += [
url(r'^media/(?P<path>.*)$', serve, {
'document_root': settings.MEDIA_ROOT
}),
]
The missing function patterns from the old example was an old function I believe used on Django 1.6 or 1.7.
After installing ckeditor, perform the following :
In Settings.py:
add 'ckeditor' and 'ckeditor_uploader' into INSTALLED_APPS.
Add CKEDITOR_UPLOAD_PATH = 'uploads_directory/'
(Do not join MEDIA_ROOT with the upload_directory, ckeditor will take the MEDIA_ROOT as its root upload directory)
In your models files:
USE : from ckeditor_uploader import RichTextUploadingField and modify your required model field to type RichTextUploadingField
In urls.py:
add re_path(r'^ckeditor/', include('ckeditor_uploader.urls')) into urlpatterns
Using Django 1.8 with django-ckeditor 5.3.0, I was getting the exact same symptoms as those above (uploading files worked, but the src attribute of the <img> tag was set incorrectly, causing a red "X" in the preview and broken image links upon publication).
In my case, however, I didn't have to change anything in urls.py. My problem was that I had:
CKEDITOR_UPLOAD_PATH = os.path.join(MEDIA_ROOT, "ckeditor")
So my mistake was giving CKEDITOR_UPLOAD_PATH the path where I wanted ckeditor to upload to (logical, no?).
The fix was to change the above line to
CKEDITOR_UPLOAD_PATH = "ckeditor"
In hindsight I can see how this allows django-ckeditor the ability to use the MEDIA_ROOT for uploading and the MEDIA_URL for serving. Still I thought someone should say it: "Don't use the full path when setting CKEDITOR_UPLOAD_PATH!"
I hope this saves others some time.
For Django 4 the steps to enable image or file upload in django-ckeditor is:
1. Install django-ckeditor
pip install django-ckeditor
2. Update settings.py
Add file upload path:
CKEDITOR_UPLOAD_PATH = "uploads/"
Add ckeditor,ckeditor_uploader in INSTALLED_APPS:
INSTALLED_APPS = [
...
# plugins
'ckeditor',
'ckeditor_uploader'
]
3. Update urls.py
Add path('ckeditor/', include('ckeditor_uploader.urls')) in urlpatterns:
urlpatterns = [
...
path('ckeditor/', include('ckeditor_uploader.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
4. Use RichTextUploadingField in models
from ckeditor_uploader.fields import RichTextUploadingField
class ResearchTopic(models.Model):
title = models.CharField(max_length=200)
description = RichTextUploadingField()
Tested with:
Django==4.0.4
django-ckeditor==6.4.0
References:
django-ckeditor documentation
The #Mohammed-tayab's solution worked for me with a little modification:
from ckeditor_uploader.fields import RichTextUploadingField
I have been using this code to produce a file uploader and I can only get as far as getting the template to attempt an upload. I am wondering if I need to either configure Apache, add something to Django settings or install some more libraries maybe?
I have followed all the steps mentioned on that page, but please ask if you suspect I may have carried one or two of them out incorrectly.
Error
jssor.slider.js
Error INTERNAL SERVER ERROR
Settings.py
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django_file_form',
'django_file_form.ajaxuploader',
'jfu',
)
TEMPLATE_CONTEXT_PROCESSORS = (
'django.core.context_processors.request',
'django.core.context_processors.static',
'django.contrib.auth.context_processors.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',
)
STATIC_ROOT = '/Users/Jonathan/Documents/django/bible/bible/static/jfu'
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(os.path.dirname(__file__), 'static').replace('\\','/'),
)
views.py
from django.conf import settings
from django.core.urlresolvers import reverse
from django.views import generic
from django.views.decorators.http import require_POST
from jfu.http import upload_receive, UploadResponse, JFUResponse
#require_POST
def upload( request ):
# The assumption here is that jQuery File Upload
# has been configured to send files one at a time.
# If multiple files can be uploaded simulatenously,
# 'file' may be a list of files.
file = upload_receive( request )
instance = YOURMODEL( file = file )
instance.save()
basename = os.path.basename( instance.file.path )
file_dict = {
'name' : basename,
'size' : file.size,
'url': settings.MEDIA_URL + basename,
'thumbnailUrl': settings.MEDIA_URL + basename,
'deleteUrl': reverse('jfu_delete', kwargs = { 'pk': instance.pk }),
'deleteType': 'POST',
}
return UploadResponse( request, file_dict )
#require_POST
def upload_delete( request, pk ):
success = True
try:
instance = YOURMODEL.objects.get( pk = pk )
os.unlink( instance.file.path )
instance.delete()
except YOURMODEL.DoesNotExist:
success = False
return JFUResponse( request, success )
urls.py
from django.conf.urls import patterns, include, url
from bible import views
from django.contrib import admin
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'bible.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^verses/', views.index),
url(r'^search/', views.search),
url(r'^contact/', views.contact),
url(r'^profile/', views.profile),
url(r'^register', views.register),
url( r'upload/', views.upload, name = 'jfu_upload' ),
# You may optionally define a delete url as well
url( r'^delete/(?P<pk>\d+)$', views.upload_delete, name = 'jfu_delete' ),
) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
models.py
from django.db import models
from django.forms import ModelForm
from django.conf import settings
# Create your models here.
class Photo( models.Model ):
file = models.FileField( upload_to = settings.MEDIA_ROOT )
The issue was with the database. I think it was corrupted somehow and wouldn't talk with the application properly. Rebuilding it and running python manage.py migrate seemed to do the trick.
Im getting a
templatedoesnotexistat / login.html
I copied and paste the settings from another project that worked and can not figure out why it can not find the template files. I have gone over it many times and copied the paths so they should defiantly be right. Its driving me mad
My file structure is
-virtual
-src
-logins
-dashboards
-static
-templates
-login.html
-static
-static-only
-media
settings.py
import os
BASE_DIR = '/Users/user/Documents/Python/virtual/'
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'logins',
'dashboards',
)
ROOT_URLCONF = 'src.urls'
STATIC_URL = '/static/'
TEMPLATE_DIR = (
'/Users/user/Documents/Python/virtual/src/static/templates',
)
if DEBUG:
MEDIA_URL = '/media/'
STATIC_ROOT = '/Users/user/Documents/Python/virtual/src/static/static-only/'
MEDIA_ROOT = '/Users/user/Documents/Python/virtual/src/static/media/'
STATICFILES_DIRS = (
'/Users/user/Documents/Python/virtual/src/static/static/',
)
urls.py
from django.conf.urls import patterns, include, url
from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^$', 'logins.views.login', name='login'),
url(r'^/accounts/auth/$', 'logins.views.auth_view', name='auth_view'),
url(r'^/accounts/dashboard/$', 'dashboards.views.dashboard', name='dashboard'),
url(r'^/accounts/logout/$', 'logins.views.logout', name='logout'),
url(r'^/accounts/invalid/$', 'logins.views.invalid', name='invalid'),
url(r'^admin/', include(admin.site.urls)),
)
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
views.py
from django.shortcuts import render, render_to_response, RequestContext
from django.http import HttpResponseRedirect
from django.contrib import auth
from django.core.context_processors import csrf
def login(request):
c = {}
c.update(csrf(request))
return render_to_response('login.html', c)
def auth_view(request):
username = request.POST.get('username', '')
password = request.POST.get('password', '')
user = auth.authenticate(username=username, password=password)
if user is not None:
auth.login(request, user)
return HttpResponseRedirect('/accounts/dashboard')
else:
return HttpResponseRedirect('/accounts/invalid')
def logout(request):
return render_to_response('logout.html')
def invalid(request):
return render_to_response('invalid.html')
You have TEMPLATE_DIR in your settings. It should be TEMPLATE_DIRS.
I doubt your template directory is inside the static directory: remove that part of TEMPLATE_DIRS.
In Django 1.8 template_dirs has been deprecated and is now expected to be defined using TEMPLATES["DIRS"]
The DIRS option
Changed in Django 1.8:
This value used to be defined by the TEMPLATE_DIRS setting.
Reference https://docs.djangoproject.com/en/1.8/ref/templates/api/#loader-types
Posting this as answer, since I wasted few hours on identifying the solution.
Using python 2.7, django 1.4.1, filebrowser 3.5.0, grappelli 2.4.2, win7 x64
So heres my problem:
Im creating a object, and trying to attach an image to it:
Clicking on search:
Navigating through folders to get to my file, and picking it:
After i pick it, this is the path it returns:
Attaching model itself:
class EntryManager(models.Manager):
def active(self):
return super(EntryManager, self).get_query_set().filter(is_active=True)
class Services(models.Model):
name = models.CharField(max_length = 20, help_text = 'Nazwa oferowanej usługi', verbose_name='Usługa')
slug = models.SlugField(max_length=255, help_text = 'Odnośnik, generowany automatycznie na podstawie nazwy', unique=True,verbose_name='Odnośnik')
icon = FileBrowseField(verbose_name='Ikona', max_length=255, directory="images/", extensions=[".jpg",'.png','.gif'], blank=True, null=True,help_text = '.jpg, .png, .gif')
is_active = models.BooleanField(help_text='Zaznacz aby obiekt był widoczny dla użytkowników', default=False)
objects = EntryManager()
class Meta:
ordering = ['name']
verbose_name = "Usługę"
verbose_name_plural = "Usługi"
def __str__(self):
return self.name
def __unicode__(self):
return self.name
def get_absolute_url(self):
return '/uslugi/%s/' % self.slug
I have no idea where to search for a problem at the moment, could any1 help?
edit:
urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
from filebrowser.sites import site
#when on dev, serve media files
from django.conf import settings
urlpatterns = patterns('',
url(r'^grappelli/', include('grappelli.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^admin/filebrowser/', include(site.urls)),
url(r'^uslugi/?$', 'services.views.services'),
)
#when on dev, serve media files
if settings.DEBUG:
# static files (images, css, javascript, etc.)
urlpatterns += patterns('',
(r'^media/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT}))
and part of settings.py
import os
PROJECT_DIR = os.path.abspath(os.path.dirname(__file__) + "../../")
MEDIA_ROOT = os.path.join(PROJECT_DIR, 'site_media/media')
STATIC_ROOT = os.path.join(PROJECT_DIR, 'site_media/static')
ADMIN_MEDIA_PREFIX = os.path.join(PROJECT_DIR, 'site_media/admin_media')
INSTALLED_APPS = (
'grappelli',
'filebrowser',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'services'
)
After reading yours urls.py I need to show You Documentation:
In your url.py import the default FileBrowser site:
from filebrowser.sites import site
and add the following URL-patterns (before any admin-urls):
urlpatterns = patterns('',
url(r'^admin/filebrowser/', include(site.urls)),
)
So only differences between You and my new project are:
I'm using Linux Ubuntu x86 on VirtualBox undex Windows 7
I have /admin/file-browser BEFORE any admin-urls:
from django.conf.urls import patterns, include, url
from django.contrib import admin
from filebrowser.sites import site
from django.conf.urls.static import static
from django.conf import settings
admin.autodiscover()
urlpatterns = static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) + patterns('',
url(r'^grappelli/', include('grappelli.urls')),
url(r'^admin/filebrowser/', include(site.urls)),
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^i18n/', include('django.conf.urls.i18n')),
url(r'^', include('django.contrib.flatpages.urls')),
)
I'm using, in a Django 1.3 project, a CDN for media resources like images, css and such. I have a problem serving admin resources, what I made is:
In settings.py:
MEDIA_URL = 'http://cdn.test.com/'
ADMIN_MEDIA_PREFIX = '/admin_media/'
In INSTALLED_APPS:
'django.contrib.staticfiles',
And in urls.py:
(r'^admin_media/(.*)', 'django.views.static.serve',
{'document_root' : 'django/contrib/admin/media/',
'show_indexes' : True}),
Looking at the admin HTML I see something like /admin_media/css/base.css but all resources return http 404. I can't understand what is wrong.
Many thanks.
Try the following:
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
# (... other urls ...)
)
urlpatterns += staticfiles_urlpatterns()
Also, the document_root you refer to in your urls.py should be an absolute path: this might also cause some issues. The above should replace this for your Django version, though.