I have many CSS files inside SITE_ROOT/sources/css and I want to compress only one file in SITE_ROOT/static/css using django-pipeline.
STATIC_ROOT = os.path.join(SITE_ROOT, 'static')
STATICFILES_DIRS = (
os.path.join(SITE_ROOT, 'sources'),
)
PIPELINE_CSS = {
'responsive': {
'source_filenames': (
'css/smartphones.css',
'css/tablets.css',
),
'output_filename': 'css/responsive.min.css',
}
}
After running collectstatic I see in the static/ folder the minified file (responsive.min.css) but there is also a copy of all files located in the sources/ folder and a copy of django admin static files.
How can I get only the minified file in the STATIC_ROOT folder?
You can create your own STATICFILES_STORAGE class, inherited from PipelineStorage, which expand the behavior of PipelineMixin. Something like this (need to be tested):
import shutil
import os.path
from django.conf import settings
from pipeline.storage import PipelineStorage
class PipelineCleanerStorage(PipelineStorage):
def post_process(self, paths, dry_run=False, **options):
# Do the usual stuff (compress and deliver)
res = PipelineStorage.post_process(self, paths, dry_run=False, **options)
# Clean sources files there
shutil.rmtree(os.path.join(settings.BASE_DIR, "static/sources"))
yield res
and use it in your settings.py instead of PipelineStorage.
Another way could be to run an automated task to clean this directory after each collectstatic. It would be the same idea but on the manage command itself.
Related
I am using Python PIL library in Django Rest Framework for building qr code and saving it to static directory.
def generate_qr(self, name):
qr = qrcode.QRCode(
version=1,
error_correction=qrcode.constants.ERROR_CORRECT_M,
box_size=15,
border=5
)
qr.add_data(name)
qr.make(fit=True)
img = qr.make_image(fill='black', back_color='white')
img.save(settings.STATIC_ROOT+"/asset-tags/name.png")
return(name+ '.png')
settings.py for media and static urls:
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
MEDIA_URL = "/mediafiles/"
MEDIA_ROOT = os.path.join(BASE_DIR, "mediafiles")
But while saving it throws an error saying /usr/app/static/name.png : no file or directory.
I am creating new file so how can it find the image in given folder.
Any Help will be appreciated. Thanks.
The qrcode package or Pillow package won't create a directory if it doesn't exist. So, as per your settings, the STATIC_ROOT is located at /staticfiles and make sure that the directory named staticfiles (and it's sub-directories) exists before runs your script.
In other words, the statement img.save(settings.STATIC_ROOT+"/asset-tags/name.png") supposed to be save the QR code image under this path /staticfiles/asset-tags/name.png and make sure the directory /staticfiles/asset-tags/ exists in your project path.
NOTE: Use settings.MEDIA_ROOT instead of settings.STATIC_ROOT would be more appropriate.
My project folders is :
mrdoorbeen
manage.py
mr_doorbeen
setting.py
mrdoorbeen
migrations
templates
index.html
profile
profile.html
I want to include a image in my profile.html file.
i use {% load staticfiles %} in top of the profile.htmland use this code at image source :
<img src="{% static "image/example.jpg" %}" alt="cant'load"/>
and i make a folder in a mr_doorbeen and call it static and in static folder make a image folder and image i put a example.jpg but it doesn't work . my static folder path is wrong or what?
where should i put my static folder in this project
For the given directory structure, You can put your static files on same level as of the directory with file, mr_doorbeen/settings.py
mrdoorbeen
manage.py
mr_doorbeen
setting.py
mrdoorbeen
migrations
templates
index.html
profile
profile.html
static/
You can set the static files to the said location as follows.
# Static files configurations.
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
The problem is with your settings file where you need to define STATIC_URL. Just follow the description in Django's documentation.
I had this same problem and solved it by adding to my settings file the import of os from pathlib and the STATICFILES_DIRS line provided in one of the other responses:
from pathlib import Path, os
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
STATIC_URL was already properly specified to '/static/'. I couldnt solve the problem with just the STATICFILES line until I realized os is a function in pathlib that needed to be imported first.
Also, in addition to importing os and adding the line just mentioned, copying the image files under static directly from within a folder that was under static (named after the app) was key to making it work. I kept the files in the folder under static too so there was redundancy.
After I did that, it worked, and then I could then delete the image files under static directly (not touching those within the folder under static) and it still worked. Somehow, copying them directly under static "taught" Django to access the files within the folder under static, which I dont understand, but it worked.
So i've been googling this issue for the past hour and can't come up with a solution. Basically this is it: in my model.py i have a class that has this
class Case(models.Model):
zoomOutImage = models.ImageField('Label', upload_to="zoomOutImage")
and in my settings.py i have my media URL/ROOT set up like this
MEDIA_ROOT = os.path.join(os.path.abspath(''),'app/static/ds/')
MEDIA_URL = '/static/ds/'
which from the webserver should serve out like this:
http://127.0.0.1:8000/static/ds/zoomOutImage/actinic_granuloma_3.jpg
I've installed PIL (inside virtualENV) and there are no errors in uploading, the only issue is when i try uploading the file via the admin panel nothing happens. No errors nothing. The file just simply doesn't get uploaded to the zoomOutImage folder by the development server. Can anyone point me towards why?
I guess your file is in a subdir of your root, subdir named 'zoomOutImage'. Or even a file called like that in the root. I remember putting a function call in the upload to string. That function creates a path and filename, using os.join and the filename from the instance. Doing this by head, no example code available right now. But must be able to google this.
Look here https://stackoverflow.com/questions/1190697/django-filefield-with-upload-to-determined-at-runtime
And by the way, I totally disagree with your answer, you should NEVER use absolute paths in your settings! See this answer use css in django 1.4 development for how to use the correct settings and refer to your Project PATH
EDIT (after reading your own answer)
Guess you are missing this first step:
this is the path to your settings.py file:
SETTINGS_DIR = os.path.dirname(os.path.realpath(__file__))
and than this is the path to your project dir: (I Am using buildout, so call it buildout, but it's the root of your project):
BUILDOUT_DIR = os.path.abspath(os.path.join(SETTINGS_DIR, '..'))
and from there on you can define everything you want:
STATIC_ROOT = os.path.join(BUILDOUT_DIR, 'var', 'static')
STATIC_URL = '/static_media/'
MEDIA_ROOT = os.path.join(BUILDOUT_DIR, 'var', 'media')
MEDIA_URL = '/media/'
and in your template file refer to the image like:
<img src="{{MEDIA_URL}}{{ case.zoomOutImage }}" width="100%">
when your object given to the template is called case
about your question of the urls.
you should add this:
if settings.DEBUG:
urlpatterns += patterns('',
(r'', include('staticfiles.urls')),
)
and see the link above to the question about using css, it's the same problem, but there for finding the css files during development. It's all about the static file places.
import os
# get abspath
def rel(*x):
return os.path.join(os.path.abspath(os.path.dirname(__file__)), *x)
MEDIA_ROOT = rel('media')
MEDIA_URL = '/media/'
STATIC_URL = '/static/'
STATIC_ROOT = '' #if only your static files are in project folder
STATICFILES_DIRS = ( rel('static'),) #if only your static files are in project folder
use this settings, and everything will work
so i finally solved my problem. For anyone having this issue in the future do the following:
if you're trying to serve static media files locally on the development server use absolute paths for MEDIA_ROOT and MEDIA_URL.
I know many people have asked, this question, but despite hardcoding the path to my template directory I can't seem to get Django to find my template.
Here is settings.py
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
#django.template.loaders.eggs.Loader',
)
TEMPLATE_DIRS = (
"/Users/full/path/to/marketing_site/templates",
)
This is the views.py file:
def static (request, feature_page):
# this will get the appropriate feature page template.
template = loader.get_template('features/pricing.html')
c = RequestContext(request,{
})
return HttpResponse(template.render(c))
Inside the main folder is the templates folder and the app folder. I use to put the apps in the same folder as settings.py but it appears django 1.4 has changed the default file structure.
My error is:
TemplateDoesNotExist at /features/pricing
Django tried loading these templates, in this order:
Using loader django.template.loaders.filesystem.Loader:
Using loader django.template.loaders.app_directories.Loader:
/Library/Python/2.7/site-packages/django/contrib/auth/templates/feature_pricing.html (File does not exist)
Update:
My logs for the webpage list the TEMPLATE_DIRS as ().
If I put a print statement on the settings.py page for the TEMPLATE_DIRS I get a printout of the TEMPLATE_DIRS appropriately... so somehow the TEMPLATE_DIRS isn't being used (from what it looks like)
I had added in an extra TEMPLATE_DIR in the settings.py
:(
it's better to set up relative paths for your path variables. You can set it up like so:
import os
PATH_PROJECT = os.path.realpath(os.path.dirname(__file__))
...
...
TEMPLATE_DIRS = (
PATH_PROJECT + '/templates/'
)
Also assuming you are using windows you may want to try:
TEMPLATE_DIRS = (
"C:/Users/full/path/to/marketing_site/templates",
)
I'm betting /Users/full/path/to/marketing_site/templates does not contain a features directory, or /Users/full/path/to/marketing_site/templates/features does not contain a pricing.html file.
Based on your comment, it looks like you're calling loader.get_template('feature_pricing.html'), instead of using 'feature/pricing.html'.
EDIT: I didn't notice this before:
Inside the main folder is the templates folder and the app folder. I use to put the apps in the same folder as settings.py but it appears django 1.4 has changed the default file structure.
That could be causing the issue. Change the directory structure to match the 1.4 Django conventions. You might just recreate the project, copy the relevant settings over into the newly create settings.py, and copy all the files.
Try adding project paths to django.wsgi
import os
import sys
paths = ('path/to/project/',
'path/to/more /included/directories/',
)
for path in paths:
if path not in sys.path:
sys.path.append(path)
os.environ['DJANGO_SETTINGS_MODULE'] = 'project.settings'
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
I am trying to understand the static structure django 1.3 tries to pursue:
I have a Project with this structure:
Project
someapp
static
someapp
css
etcetera
models.py
views.py
urls.py
urls.py
manage.py
settings.py
Now I wish to overwrite the django admin.. So I have to set these settings in settings.py which I did like below (basepath is the shortcut path to the current directory):
# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/media.lawrence.com/static/"
STATIC_ROOT = BASE_PATH+'/static/'
# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'
# URL prefix for admin static files -- CSS, JavaScript and images.
# Make sure to use a trailing slash.
# Examples: "http://foo.com/static/admin/", "/static/admin/".
ADMIN_MEDIA_PREFIX = '/static/admin/'
# Additional locations of static files
STATICFILES_DIRS = (
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
If I use the manage.py command collectstatic, it collects all static files (including the admin files) in a directory 'static' as expected... (within the main project dir)
However it's content isn't served yet until I add that directory to the STATICFILES_DIRS tuple, however then I have to change the STATIC_ROOT directory setting because otherwise I'll get the error they cannot be the same...
I think I am overlooking the obvious because what I have to do to make it work seems redundant
For local development, try this structure
Project
Project (project directory with settings.py etc..)
stylesheets
someapp
static
base.css
With this in settings.py:
import os
ROOT_PATH = os.path.dirname(__file__)
STATIC_ROOT = os.path.join(ROOT_PATH, 'static')
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(ROOT_PATH, 'stylesheets'),
)
Run the local server with python manage.py runserver and go to http://localhost:8000/static/base.css
You should see the stylesheet.
STATICFILES_DIRS is a setting you use to declare non app-specific static files live in your project. STATIC_ROOT is where the static files get placed when they are collected.
From django's docs:
"Your project will probably also have static assets that aren’t tied to a particular app. The STATICFILES_DIRS setting is a tuple of filesystem directories to check when loading static files. It’s a search path that is by default empty. See the STATICFILES_DIRS docs how to extend this list of additional paths."
"Set the STATIC_ROOT setting to point to the filesystem path you'd like your static files collected to when you use the collectstatic management command."
How about:
STATICFILES_DIRS = (
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
STATIC_ROOT,
)