Problem while loading static files|| django - django

iam learning Django i have learned pretty much. I used static method to rendered css and other static files. But changes iam making to css which is in static files are not reflacting on webpage . i have to close all files and restart vscode again to see those changes. I have not added code because im not getting any error at all .
( example :: i have changed font size of all anchors . Normally it should be changes on webpage after saving and refreshing the page. but in this case font size is not changing. i have to close all files and reopen them and after starting the server again i can see those changes which i made to anchor tag. )
Any one who knows why because to see changes restart whole project will never be a good option. thanks in Advance

At the beginning of your code use {% load static %} and where ever you want to use the files from static folder use {% static 'name of your file' %}
Make sure you've not added your static folder in your base directory. In such case update your settings.py
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static')
]
STATIC_ROOT = os.path.join(BASE_DIR, 'assets')
you can use whichever name you like instead of assets

Related

Django : Page Not Found when trying to access static files

I know there are already several threads on the topic. I've been through most of them (especially all the troubleshooting listed in this one) but I can't figure out my issue.
I am trying to use a Bootstrap template in my Django project, and I'd like to simply start by accessing the files in the /static/ directory. My project directory looks like this :
Whenever I try to load the page http://localhost:8000/static/theme/assets/css/style.css it returns a Page not found error (and obviously no CSS/JS content appears on my index).
Here are my settings:
I have debug = True
ÌNSTALLED_APPS contains django.contrib.staticfiles
settings.py looks like this :
STATIC_URL = "/static/"
STATICFILES_DIRS = (os.path.join(BASE_DIR, "static/"),)
But I still can't access anything from the /static/ directory.
I tried to access the CSS and JS files in base.html this way :
{% load static %}
...
<link href="{% static 'theme/assets/css/style.css' %}" rel="stylesheet">
I really have no clue how I could solve this.
Thanks in advance for your help !
Is base.html properly bound to a URL and to a view function via a URL dispatcher ? Can you access that file from your browser ?
If yes, try to substitute this line
STATICFILES_DIRS = (os.path.join(BASE_DIR, "static/"),)
with this one
STATICFILES_DIRS = (os.path.join(BASE_DIR, "static"),)

How can I apply bootstrap to my whole django project?

I've been looking at a few guides on applying bootsrap to django, and I am as far as having a static file in the root of my site, containing the css and js files within bootstrap, but when it comes to linking the files I am having an issue.
So I am trying to link the stylesheet inside of my base.html file but am not sure how to format it as for some reason using {% %} inside of the href field is being interpreted as part of the directory. In one of the videos I have watched he links it like thisBut I'm not really sure how to interpret this as trying to apply it to my own like so
href = "{% static 'artForAll/css/bootstrap.css' %}"
With the file structure for reference:
\AFA\src\artForAll\static\artForAll\css
I am given an error about a non existent file as it is taking the {%%} as part of the directory
My settings.py
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR,"static"),
]
File structure(blue highlighted file is where BASE_DIR leads:

Change Django static directory name

Django static directory name is set to static by default. Can it be changed to something else?. If i could change it to cssandjs could this bring any errors to my project? and does that also mean that in templates i would load static by {% load cssandjs %} instead of {% load static %}?
the statics files con also be loded from more than one directory, this can be defined by this setting, this is where django search your files inside your server
STATICFILES_DIRS = [
BASE_DIR / "static",
'/var/www/static/',
'/some_folder/cssandjs',
]
thats why you put the files inside apps folder, to avoid overlapping
the url is defined by this setting, this is what you see on the web browser
STATIC_URL = '/static/'
in your template you always use {% load static %}, and django search in all your folders
https://docs.djangoproject.com/en/3.1/howto/static-files/

Django and OpenShift static files can't be found

So I followed this tutorial:
https://github.com/rancavil/django-openshift-quickstart/wiki/Tutorial-How-create-an-application-with-Django-1.6-on-Openshift
and I tried to add a static image to the default home.html page and it just won't find it.
HTML:
{% load static %}
<html>
<head>
</head>
<body>
<img src="{% static 'Logo_Trans.png' %}">
<div class="left"></div>
<div class="right">
<p>is coming soon</p>
</div>
</body>
</html>
All other files are as listed in the repo given.
I've found the problem. The static files were serving properly when deployed but not when in debug mode. To fix this just add the STATICFILES_DIR variable in settings.py
Find:
if ON_OPENSHIFT:
DEBUG = False
else:
DEBUG = True
Add:
if ON_OPENSHIFT:
DEBUG = False
else:
DEBUG = True
STATICFILES_DIRS = (os.path.join(BASE_DIR, "static"),
'/var/www/static/',)
Openshift is a very good service but definitely needs to update their docs/examples for django. Their sample program still runs django 1.4. Hope this helps anyone else that runs into this problem.
you can read the answer for this question Django cannot find static files. Need a second pair of eyes, I'm going crazy. Hope it will help you to understand static files. Static files in Django are always a bit painful.
Btw, as I explain in the last comment, I recommend you to create an app called common within a static folder inside it to place static content that is not application specific. Static application specific files should be placed inside the static folder within your app. This way, you can forget about defining the STATICFILES_DIRS variable and it will always work in DEBUG mode.
After that, ofc, define STATIC_ROOT and when you want to work in deploy mode, do the collectstatic command and it will also work.
After dealing hundreds of times with issues like this, I've found this is the best approach.

What am I doing wrong with Django static files?

I am working on writing a Django app for the first time, so bear with me if I'm a little behind on things.
Here is an excerpt from my settings.py:
STATIC_ROOT = os.getcwd().replace('\\','/') + '/static'
STATIC_URL = '/static_files/'
STATICFILES_DIRS = (
os.getcwd().replace('\\','/') + '/static'
)
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
Note: I'm hoping that the os.getcwd()... line works. I am pretty sure it's not my problem, but please let me know if this is an issue. It's a placeholder for local dev purposes, so don't worry about it remaining there when I deploy.
My first issue is that template variables don't seem to be working.
An excerpt from my main template file:
<link rel="stylesheet" type="text/css" href="{{ STATIC_URL|default:'/static_files/' }}css/base.css" />
I originally just had {{ STATIC_URL }} in there, but that simply returned nothing, so I tried adding |default:'...'. This did successfully generate the given string in the resulting HTML, but still didn't work, which brings me to my second (and more important, honestly) issue.
I can't get static files to work at all. I have tried several different methods here. I have tried putting absolute and relative paths (in various combinations) in each of the above STATIC_* variables, I have tried using the equivalent MEDIA_URL vars instead, and I have tried putting the following into my urls.py:
urlpatterns = ('',
# ...
(r'^static_files/(?P<path>.*)$',
'serve', {
'document_root': '/path/to/django/dir/static_files/',
'show_indexes': True
}
),
)
(I grabbed the above snippet from http://www.arthurkoziel.com/2008/09/02/handling-static-files-django/.)
Now I should note that I will hopefully be eventually serving up static files from a parallel Apache process once initial dev is completed, but I would still really like to know what I'm doing wrong. I haven't been able to find a decently comprehensive tutorial on static files online or on StackOverflow.
All help is greatly appreciated.
EDIT: In case it is important, I am on Windows 7 using Python 2.7.
One possibility - STATIC_URL won't be filled out in your templates unless you're passing in a RequestContext.
Make sure you have something like this in your views:
return render_to_response(template, context, context_instance=RequestContext(request))
As of Django 1.3 you can also use the new shortcut:
return render(request, template, context)
Also, make sure you have 'django.core.context_processors.static' in your context processors.
EDIT: Possible answer to the second problem, try changing
STATICFILES_DIRS = (
os.getcwd().replace('\\','/') + '/static'
)
to
STATICFILES_DIRS = (
os.getcwd().replace('\\','/') + '/static',
)
EDIT 2: More possible fixes
You can delete STATICFILES_FINDERS. You only have it set to the default, so unless you intend to expand it later on, get rid of it (one less thing to go wrong).
You can also get rid of the urlpatterns entry. Not necessary.
Your STATIC_ROOT is probably incorrect. This should be the place where Django will gather all the static files from across your project (including the directories described in STATICFILES_DIRS) when you move to production.
An example from a typical settings.py of mine:
PROJECT_DIR = os.path.dirname(__file__)
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(PROJECT_DIR, 'static'),
)
STATIC_ROOT = '/var/www/myproject_staticfiles/'
That's it!
If you want to test whether Django is finding and placing your static files correctly, try running
python manage.py collectstatic
In my case, that would go through my project directories, find all the static files, then copy them across to '/var/www/myproject_staticfiles/', where I can host them with apache.
The Django dev server automagically serves static files from within your project folder, so no collect_static is required while in dev. You don't even need to set STATIC_ROOT until you go into production.