Managing URLs in a Django site inside a folder - python

So I have my Django project in a folder on my server, like so:
www.mydomain.com/myfolder/
The index page loads, but things like the css document don't because the paths are improper. Am I missing a shortcut? I looked through the settings.py documentation for a place to specify my site folder, but didn't find anything to help.
So example, if I specify this in my settings:
STATIC_URL = 'static/'
Then it will look for my css doc on my /myfolder/login page at:
http://mydomain.com/myfolder/login/static/stylesheet.css
If I specify:
STATIC_URL = '/static/'
Then it will look for my css doc on my /myfolder/login page at:
http://mydomain.com/static/stylesheet.css
Meanwhile, my css document is at:
http://mydomain.com/myfolder/static/stylesheet.css
Do I need to change everything and specify /myfolder/ before everything?

I think you need to add path of you STATIC_ROOT in settings, and update urls.py file.
My example:
#settings.py
....
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static",)
#path to your static folder
#urls.py
...
from django.conf import settings
from django.conf.urls.static import static
....
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

This question has a good practice solution on django tutorial:
See:
https://docs.djangoproject.com/en/1.6/intro/tutorial06/#customize-your-app-s-look-and-feel
That you should create a /static/appname/ folder inside each of your app, and then put the static files inside it.
So in your app, the static file url should turned into something like:
http://mydomain.com/static/app_name/stylesheet.css
Which won't collides with other app.
You'd better read the link I offered above, the tutorial shows a good habit.

Don't you just need to do this?
STATIC_URL = '/myfolder/static/'

Related

Django admin site not loading CSS

Not sure what is going on, but my admin page on my Django site isn't loading any CSS. Not sure if it has to do with python manage.py collectstatic but ever since I served my static files using this, my admin page doesn't load with CSS and instead, it's plain HTML. This same issue is happening with a few projects of mine when using collectstatic. Any ideas? They'd be appreciated. Since I don't know what the issue is or where to start, I'm not sure what code to provide. If you want to see anything, let me know.
I've noticed when I viewed the source of the admin page and clicked on the css links (<link rel="stylesheet" type="text/css" href="/static/admin/css/base.css">), the base.css file seems to be corrupted maybe ? What the base.css looks like All the other css files when clicked are readable. What the other css files look like
Add the following code to the settings.py file
PROJECT_DIR = os.path.dirname(os.path.abspath(__file__))
STATIC_ROOT = os.path.join(PROJECT_DIR, 'static')
STATIC_URL = '/static/'
After that add the following in the URL:
static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

Get the path of "static" folder in django automatically

I am developing Django (1.6) app. In my app I have to use the static images to be displayed on the HTML pages (like magnifying glass for search box,logo,etc). After little bit of research I came to know that we have to create a folder (say "static") which holds the static images and then I have mention the path in my settings.py like shown below :
`STATIC_URL = '/static/'
STATICFILES_DIRS = (
"C:/Users/Welcome/Desktop/business/static/polls",
"C:/Users/Welcome/Desktop/business/static",
)`
I also added the code shown below in urls.py too after which I could get the images on my HTML pages.
urlpatterns = patterns(''......... ...........) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
My question now is every time I change the directory (current working directory or if I transfer the project to another pc ) I have to update the path in settings.py.
How to not do that ? how to get path of "static" folder automatically when I run my project. Please do help. What I'm missing ?
Normally the static files finder of django will expect that your app itself has a static sub-directory, and you can store everything there.
+ myproj
- manage.py
+ app
- __init__.py
- settings.py
- urls.py
+ static <-- notice the static directory.
+ templates
This is good of course for development where the Django server is the one serving these static files. In production you'll need to collect everything to the location declared in your STATIC_ROOT setting with the collectstatic management command.
This way you won't need to change the location each time you copy your project to a new location or a new computer.
Of course, that once you do that you can drop the STATICFILES_DIRS definition from your settings.py. This setting is used to tell Django that there are other static assets that reside outside of a certain app. If you want to use it anyway then you can define those directories relative to the project itself, i.e.:
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static")
)
Your urls.py should then use the staticfiles_urlpatterns like this:
if settings.DEBUG:
urlpatterns += staticfiles_urlpatterns()
For more information see the Django documentation on static files:
https://docs.djangoproject.com/en/1.7/howto/static-files/
I just figured out the solution for my question. First you need to get the current working directory and then for looking out for the folder in that current working directory(where your project is being installed) assign this to variable say path_for_images and then pass it to the STATICFILES_DIR as shown below:
path_for_images = os.getcwd()+"\static"
STATICFILES_DIRS = ( path_for images,) <-- note ,(comma) after `path_for_images`
No need to do any changes for the urls.py and images get loaded. This isn't exact pythonic way but it's surely one of the way.

django ImageField not uploading the file

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.

Django static files won't load

i'm a Django newbie working on my first project and having a problem with static files.
I have created a simple auth system using django.contrib.auth consisting of two templates: mysite/templates/index.html and mysite/templates/registration/login.html. I have global static content in mysite/static which I want to be able to access on all templates rendered by all apps.
mysite/templates/index.html contains <img src="{{ STATIC_URL }}pics03.jpg"/> which renders as "static/pics03.jpg" and loads fine when I visit the url localhost:8000/
mysite/templates/registration/login.html contains <img src="{{ STATIC_URL }}pics03.jpg"/> which also renders as "static/pics03.jpg" and does not load when I visit the url "localhost:8000/accounts/login/"
In my urls.py I have:
urlpatterns = patterns('',
url(r'^$', 'mysite.views.home'), # plays index.html template
url(r'^accounts/login/$', 'django.contrib.auth.views.login'),
In my settings.py I have:
PROJECT_DIR = os.path.dirname(__file__)
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.
os.path.join(PROJECT_DIR,'static'),
)
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
STATIC_URL = '/static/'
STATIC_ROOT = ''
I was under the impression that Django should be looking for global static content in STATICFILES_DIRS, but it doesn't find the static content for login.html even if I change the url in there to an absolute path to the static folder. Can anyone shed any light on this?
Your problem is that you arent listening to the URL "/static/" nowhere in your urls.py
If you serve your application via a webserver like apache or nginx then this is normal as the webserver would handle the static files itself.
For development Django comes with a built-in static server
to urls.py, at the very end add
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns += staticfiles_urlpatterns()
What this does is to add the /static/ url and let you serve those without a webserver.
This is equivalent to
url(
regex=r'^static/(?P<path>.*)$',
view='django.views.static.serve',
kwargs={'document_root': settings.STATIC_ROOT,}
)
some people will tell you that you need to wrap the URL-rules in a "if settings.DEBUG" to use the dev-only rules, but this isnt needed at all and actually i find that to be a bad advice.
Are you having trouble when using the build in runserver or are you serving using Apache or similar? I've struggled with this a bit. The documentation I follow is: https://docs.djangoproject.com/en/stable/howto/static-files/
The second part is key when you are ready to deploy. You need to define a static root (which will be empty to begin with) and run the manage.py collectstatic command to move the static files from throughout your project into that folder. Then you can serve them from there.
Does changing STATIC_ROOT='' to STATIC_ROOT='/' help?
It seems to me the only difference is that static/pics03.jpg (relative path) exists on the home page, but doesn't on the other.
The absolute path /static/pics03.jpg exists in both cases. If changing STATIC_ROOT doesn't help, just add a / to the beginning of the urls.

Serving static media during Django development: Why not MEDIA_ROOT?

I read this guide about serving static media with Django during development.
I noticed that MEDIA_URL and MEDIA_ROOT were not used in this. Why? What's the difference?
I tried doing it with MEDIA_URL and MEDIA_ROOT, and got weird results.
In a production situation you will want your media to be served from your front end web server (Apache, Nginx or the like) to avoid extra load on the Django/Python process. The MEDIA_URL and MEDIA_ROOT are usually used for this.
Running the built in Development server you will need to set the correct url in your url.py file - I normally use something like this:
from django.conf import settings
urlpatterns += patterns('',
(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}),
)
Which picks up the MEDIA_ROOT from your settings file meaning that it works for development and live.
Straight from the comments in settings.py...
MEDIA_ROOT
The MEDIA_ROOT is the absolute path to the directory that holds media such as /home/media/media.lawrence.com/.
MEDIA_URL
The MEDIA_URL is the URL that handles the media served from MEDIA_ROOT. Make sure to use a trailing slash if there is a path component (optional in other cases). Examples: "http://media.lawrence.com", "http://example.com/media/".
So, to reword those... The MEDIA_ROOT is where the files live physically on your system, and the MEDIA_URL is where those files are mapped to. In development, this might not always be accessible, and in most cases your dev environment and your production environment are not the same, and it is something you're going to have to go back and change. The other thing is that it is NOT A GOOD PRACTICE when Django was designed NOT to serve static content for you.
If you're going to use this in development, I suggest you use the method of limiting it to DEBUG=True. Telling Django to serve static content from a temporary location while in development when the DEBUG is set to True is a much better and safer practice. You're NOT going to put your site into production with DEBUG on, right? Well, at least you shouldn't.
Here is how I implemented it:
settings.py:
STATIC_DOC_ROOT = os.path.join(os.getcwd(), 'site_media')
urls.py:
from django.conf import settings
## debug stuff to serve static media
if settings.DEBUG:
urlpatterns += patterns('',
(r'^site_media/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': settings.STATIC_DOC_ROOT}),
)
This way any project I'm working on has a site_media directory inside of it with all of the media necessary. In dev it is self-contained and I don't have to flip any bits in the settings except for DEBUG, which I would be doing anyways.
The Django docs recommend the following approach I've modified for my use case:
urlpatterns = [
# url patterns
]
from django.conf import settings
if settings.DEBUG:
from django.conf.urls.static import static
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Note: the above assumes you've set your MEDIA_URL and MEDIA_ROOT correctly
... and here's the djangodocs linkslap.

Categories

Resources