Custom stylesheets in Django (1.3) admin - css

I've got several custom stylesheets that override default admin styles. They live in myproject/static/admin/css-extended. I'm overriding several of Django's default admin templates with templates that live in 'myproject/templates/admin'.
In the templates my stylesheet references are: {{ STATIC_URL }}/admin/css-extended/[stylesheet].css.
However, I can't get the custom stylesheets to pull through.
I've got the following url-related settings in settings.py:
MEDIA_ROOT = os.path.join(PROJECT_DIR, 'media')
MEDIA_URL = '/media/'
STATIC_ROOT = os.path.join(PROJECT_DIR, 'static')
STATIC_URL = '/static/'
ADMIN_MEDIA_PREFIX = '/static/admin/'
I've got the following template context processors listed:
'django.core.context_processors.media',
'django.core.context_processors.static',
Can anyone help please?
Thanks
UPDATE:
I suspect the issue has something to do with the fact that my ADMIN_MEDIA_PREFIX is the same as the first part of the css-extended url ('/static/admin'). I guess Django is trying to find a directory called 'css-extended' in the core admin rather than in the project itself. But how do I get round this?

Are you having this problem on your local dev environment (with runserver)? If so, do you have the following in your urls.py?
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
# ... the rest of your URLconf goes here ...
urlpatterns += staticfiles_urlpatterns()
Read the Django Docs for more.

Ok, I now think I know what's going on here. Hopefully this will clarify:
STATIC_ROOT is only used by the "collectstatic" management command, to figure out where to dump the static files it collects.
STATIC_URL is used by the dev server to define the URL at which the static files will be served.
STATICFILES_DIRS, which you haven't set, is used by both the dev server and the "collectstatic" management command to identify the locations of the static files to serve. In the case of the dev server, the files are served directly in place. In the case of the management command, the files are gathered and copied into STATIC_ROOT.
[Note: there's a convention here -- if you have /static subdirectories in your apps (not your project), they'll be picked up along with anything explicitly defined in STATICFILES_DIRS.]
You just need to add the following to settings.py:
STATICFILES_DIRS = {
'/absolute/path/to/myproject/static/',
}

Related

static-files 404 not found on hosted django app

im having a hard time to display my static files on my webpages, im hosting my website on digitalocean ubuntu 18 and my static files are stored on the digitalocean space. initially everything was okay and working correctly until i added 3 new images to the server and ran the collectstatic command afterwards, note this was for the second time cause i ran it the first time to store the files in the digitalocean space folder i created. The collectstatic command shown me a warning saying
UserWarning: The default behavior of S3Boto3Storage is insecure and will change in django-storages 2.0. By default files and new buckets are saved with an ACL of 'public-read' (globally publicly readable). Version 2.0 will default to using the bucket's ACL. To opt into the new behavior set AWS_DEFAULT_ACL = None, otherwise to silence this warning explicitly set AWS_DEFAULT_ACL. "The default behavior of S3Boto3Storage is insecure and will change "
after i continue by typing yes, the files are images are successfully stored in the digital-space, but ever since i ran the collect command for the second time all staticfile are not displayed. I did some further reading about this warning and used the solution from AWS S3 and Django returns "An error occurred (AccessDenied) when calling the PutObject operation" but still nothing changed the warning went away but the staticfiles are still not found.
heres the error message from the chrome browser: Failed to load resource: the server responded with a status of 404 (Not Found)
have you ensured your settings display this:
STATIC_ROOT = os.path.join('static')
STATIC_URL = '/static/'
Following this, your templates should show the following:
<link rel="stylesheet" type="text/css" href="{% static '/locationofstatics/css/style.css' %}">
<link rel="stylesheet" type="text/css" href="{% static '/locationofstatics/css/bootstrap.css' %}">
The best way to go about things in my opinion is to only collecstatic locally and then push all of the local files and directories up to the server. What do you currently use to transfer files to the server side?
The other thing you need to do is ensure that Nginx has the location of your static files set within the sites-available file. From your ssh terminal (server side terminal) you can type:
sudo nano /etc/nginx/sites-available/projectname
Within this you need to add the location of your statics, for example:
server {
ocation /static/ {
root /home/name/projectname;
}
}
The following documents are extremely useful:
https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-16-04
https://www.digitalocean.com/community/tutorials/how-to-install-nginx-on-ubuntu-18-04
I was using nginx server in digitalocean for my django project.
front-end static files were working but admin not.
See my static files setting:
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static')
]
STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles")
front-end css in static folder and collectstatic target folder is staticfiles
So our main focus is STATIC_ROOT means staticfiles folder. In nginx settings put "staticfiles" instead of "static" to set static file location.
Your STATIC_ROOT folder name could be anything you need to use that same name in nginx.
See below code for nginx setting:
location /staticfiles/ {
root /home/[your_username]/[your_project_folder];
}
[your_username]: which you are using to host your project on digitalocean.
The whole thing is that, you need to use your STATIC_ROOT folder in nginx setting.
Command to create/edit nginx setting is:
sudo nano /etc/nginx/sites-available/[your_project_folder]

Pyexcel, loading a file to create a book in memory

This is solved; thanks to #vmontco's solution: I was missing MEDIA_URL, now it works perfectly.
----------original question below-----------
I welcome suggestions from every angle; I am fairly new to Django and Python. I'm sure I am missing something simple.
Using a Model Form, with a FileField, I upload and save an Excel file to a folder structure under MEDIA_ROOT. This works.
I want to read that same file later to perform operations using Pyexcel. This is where I am stuck. I am attempting to upload the file using the FileField stored in the DB.
This is where I have problems, and I am not sure if am misunderstanding MEDIA_ROOT, or some other aspect of Django.
When I pass the pk to the 2nd view, I then instantiate an object based on the Model. It has the FileField 'docfile', which I am trying to use to access the file to do some operations using Pyexcel,
here is the FileField declaration from models.py:
docfile = models.FileField(
verbose_name="Choose file to upload:",
upload_to='Excel_CSV_Assets/%Y/%m/%d')
EDIT: If I hard-code the pth to the file like this, everything works, including operations afterwards:
thedocfile='site_static/site/original_assets/Excel_CSV_Assets/2016/04/23/Animals_oglc4DV.xlsx'
book=pyexcel.get_book(file_name=thedocfile)
:END OF EDIT
Here is the code from the 2nd view, where I attempt to read the file into memory, and make a 'book' class object using Pyexcel. I am stuck here:
asset = Excel_CSV_Asset.objects.get(id=assetid)
book=pyexcel.get_book(file_name=asset.docfile)
Here is my error description:
Here is the info right at where my code breaks:
Although it says "Wrong filename", I can see the file is in the folder:
I'm able to open the file by double-clicking; the file is not corrupted.
EDIT:
If I cast the 'asset.docfile' to str, like so:
asset = Excel_CSV_Asset.objects.get(id=assetid)
book=pyexcel.get_book(file_name=str(asset.docfile))
I get a different error:
[Errno 2] No such file or directory: 'Excel_CSV_Assets/2016/04/23/Animals_oglc4DV.xlsx'
...but this is the correct directory, located beneath the MEDIA_ROOT file structure.
Here is settings.py MEDIA_ROOT:
MEDIA_ROOT = 'site_static/site/original_assets/'
Here is urls.py:
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^e/', include('excel_to_mongo.urls')),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
Here is the url.py of that app:
url(r'^efactory/(?P<assetid>\d+)/$', 'display_sheet_column_choices', {}),
I think your problem is that you don't fully understand the media files management with Django.
What are media files?
Media files are all the files that are user-uploaded (at running time).
You must not mistake them with Static files that are assets needed by your project to work and that you add at development time (CSS, background picture and JS files for instance).
You shouldn't mix them because they are managed differently by the server and that it could lead to security problems (cf. the warning here):
Static files management :
You put your static files as a part of the code either in one static subdirectory from the installed django applications, either in one of the locations you added to STATICFILES_DIRS.
Static files have to be gathered before starting the server by calling ./manage.py collectstatic, this command will collect (copy) the static files into the a directory (STATIC_ROOT's value).
You then have to set STATIC_URL to choose with wich url you should serve your static files. An usual choice would be /static/. To access the static file you should then try to reach /static/path/to/static/file/in/static_root/dir.
Media files management :
Your media files are added at running time. They are stored in the MEDIA_ROOT location that has to be an absolute path. Hence the fact I suggested you to join the BASE_DIR value (an absolute path) and the subdir you would choose with something like :
MEDIA_ROOT = os.path.join(BASE_DIR, "/media/subdir")
You then have to set an URL for your media files, by using the MEDIA_URL variable. To access your media files, the urls will start with the value you choose :
MEDIA_URL = '/media/'
Then, add this to your urls.py file :
if settings.DEBUG:
urlpatterns = urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
With the current example, your mymediafile.txt will be located at /path/to/your/project/media/subdir/path/in/media/root/mymediafile.txt and served at http://127.0.0.1:8000/media/path/in/media/root/mymediafile.txt.
But this is suitable only for a development use as told here. And this would work only for DEBUG == TRUE
For a production use, you should consider deploying your media files with your http server (apache for instance).
Conclusion :
Take the time to understand this. Because I suspect you don't really understood what you did and this lack of understanding could lead to future bugs and errors.

Django MEDIA_URL and MEDIA_ROOT issue with CSS

I'm having a very similar problem to this question but unfortunately none of the solutions seem to be working for me.
Essentially I have the following, really simple directory:
ulogin
- models.py
- tests.py
- views.py
- media
- screen.css
- templates
- utemplate
- index.html
in my settings.py I have the following defined:
MEDIA_ROOT = '../compwebsite/ucode/ulogin/media'
MEDIA_URL = '/media/'
and in index.html I have the following trying to reference screen.css
<html>
<head>
<title>
YAY TITLE
</title>
<link rel="stylesheet" href="{{ MEDIA_URL }}screen.css">
<!--and it more...-->
My urls.py I have the following:
from django.conf.urls import patterns, include, url
from django.conf import settings
from django.conf.urls.static import static
if settings.DEBUG:
# static files (images, css, javascript, etc.)
urlpatterns += patterns('',
(r'^media/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT}))
No matter what I do, I can't get the reference to the screen.css to work. I'm really uncertain of how to fix this based on the other questions here on the site. Thank you so much and let me know if you need more info!
Static files should be placed in the 'static' directory; this is where Django will look. The 'media' directory is meant to hold user-uploaded files, which get copied over to the static directory when the django server runs.
Change your MEDIA_URL references to STATIC_URL
You shoudn't have to use the URLConf to manage static files at all.
As for your Django settings, it's not a good idea to hard code absolute paths in case they are changed (i.e. when pushed to a deployment server).
A better idea is to do something like this:
from os import path
PROJECT_ROOT = path.abspath(path.dirname(path.dirname(__file__)))
MEDIA_ROOT = path.join(PROJECT_ROOT, 'media/')
MEDIA_URL = ''
STATIC_ROOT = ''
STATIC_URL = '/static/'
STATICFILES_DIRS = (
path.join(PROJECT_ROOT, 'static/'),
)
This will ensure that Django is using the correct absolute path regardless of where your project is on your system.
You can also enable the DefaultStoreFinder in STATICFILES_FINDERS although it shouldn't be necessary.

Django 1.3 rc1 and CSS

This is my configuration:
project_root
- (init, urls, settings, manage etc.).py
- templates
- - - <html files>
- - - <css files>
- - - <images>
- mainapp
my settings.py:
DEBUG = True
TEMPLATE_DEBUG = DEBUG
...
STATIC_ROOT = 'c:/static_collect/'
...
STATIC_URL = '/static/'
...
STATICFILES_DIRS = (
'c:/django-projects/myproject/mainapp/templates',
)
...
TEMPLATE_DIRS = ('c:/django-projects/myproject/mainapp/templates',)
my template references CSS files with {{ STATIC_URL}}style.css.
Everything works in development server. I view my CSS, static images and everything else.
Now I'm preparing to deploy a project, so I'm experimenting a little, before buying a hosting. Launched manage.py collectstatic and all of my static files in STATICFILES_DIRS were correctly copied to c:/static_collect.
I switched Debug = False to Debug = True. And my website doesn't load the stylesheet. I'm going crazy on this... templates are loaded but static files are simply not reachable.
Are not you allowed to put Debug=False in the development server?
Will it be solved once I put the project on a real production server?
Any ideas?
Thank you for your time.
The static files aren't added to the url patterns when debug is set to False. See staticfiles/urls.py:
if settings.DEBUG and not urlpatterns:
urlpatterns += staticfiles_urlpatterns()
You'll need to setup apache to serve the files, or add the urlpatterns yourself when debug is False (not recommended).

django css file not recognised - wrong configuration?

in my app, i want to use a css file, but the tempalte doesn't 'know' where the file is, though i've configured it as in tutorials:
in the urls.py (the urls file in the root of the site, not belonging to an app)
(r'^site_media/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': settings.STATIC_DOC_ROOT}),
in the template
<link href="/site_media/default.css" rel="stylesheet" type="text/css" />
in the settings:
STATIC_DOC_ROOT = '/site_media'
where can i be wrong?
Thanks
Check django-annoying, it's a very useful app with plenty of convenient decorators, middlewares and functions. If you add StaticServe middleware like that, Django will serve static if DEBUG = True without explicitly setting in urls.py.
MIDDLEWARE_CLASSES = (
'annoying.middlewares.StaticServe',
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.doc.XViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
)
Second, check your MEDIA_URL (in your case it's STATIC_DOC_ROOT, but you should use MEDIA_URL) and MEDIA_ROOT path. MEDIA_ROOT should point to absolute path to your static directory. This is how I do it in setttings.py:
import os
def rel(*x):
return os.path.join(os.path.abspath(os.path.dirname(__file__)), *x)
# MEDIA_ROOT will point to media directory where settings.py is located
MEDIA_ROOT = rel('media')
MEDIA_URL = '/media/'
You can use the same function to set path to your templates dir.
The document_root argument to static.serve needs to be the location of the file on the server filesystem, not the URL. So unless your css file really is in the /site_media directory on your disk, which seems unlikely, you want something else as STATIC_DOC_ROOT.

Resources