I have some javascript that I would like to run on a particular page of a Django site I am building. In the template I currently have:
<script type='text/javascript' src='{% static "/home_page/github_repos.js" %}'></script>
The HTML that is generated by this is:
http://localhost:8000/home_page/github_repos.js
The problem is that I have the javascript in /static/home_page/.
If I hardcode in the path as:
<script type='text/javascript' src='static/home_page/github_repos.js'></script>
Everything works fine.
However, I am getting odd behavior that I do not understand:
If, in the template I set the path like this:
<script type='text/javascript' src='{% static "static/home_page/github_repos.js" %}'></script>
The HTML generate has a src attribute of /static/static/home_page/github_repos.js
The part that is really throwing me off is that if I do not put /static/ at the front of the src when using the template tags (like the first example I give), /static/ is not added, however, if I do add /static/ at the front, it gets added. I need /static/ added to the front of the src attribute, but only once.
Some relevant information:
My home_page app resolves to '/' as the url, so localhost:8000/ gets you to the home page.
I have included'django.contrib.staticfiles' in my installed apps
Finally, STATIC_URL = '/static/'
Is this problem occurring because my home_page app resolves to the root address of localhost:8000/?
Any help is appreciated.
This issue is because the path in the static tag should be relative to the static directory. From the docs:
Uses the configured STATICFILES_STORAGE storage to create the full URL for the given relative path
You're using an absolute path. Instead, you should use:
{% static "home_page/github_repos.js" %}
Note the omission of the leading forward slash.
Related
I am new to Django and so far all I know about static files is that they are CSS, JS, and images and they should be in a directory called static within the app directory
but when I use one of these files in my template like that:
first I load the static files
{% load static %} <!-- in the 1st line of the template -->
then I link the CSS file like that
<link href="{% static 'auctions/styles.css' %}" rel="stylesheet">
They don't load and the styles don't seem to appear
so I just want to know what I am missing here
this is the project tree enter image description here
static root and url from settings
STATIC_URL = '/static/'
STATIC_ROOT = 'E:/Work/SoftwareDevelopment/Web/Django/commerce/auctions/static'
Did you ran python manage.py collectstatic?
You also need to configurate your settings.py with STATIC_URL = '/static/'
Docs
Are your auctions's static folder separated in css, js, images folders? If so, you are missing specifying that in static:
'auctions/css/styles.css'
If that doesn't work, try running collectstatic manually and getting the path to the file from there to pass in the html.
I recently updated one of my views and URLs to take an additional parameter and now that I have done this the page which is rendered displays with no css or javascript because the static path is wrong.
I am obviously not understanding correctly how static is served however I didn't think that changing the URL confs would change the path that Django would look for static. All my static for the whole site is in the one place.
urls.py
url(r'^fill/(.*)/(.*)/$', views.fill_survey, name='unique_getfile'),
url(r'^fill/(.*)', views.fill_survey, name='unique_getfile'),
and here is my view ... first block executes for the first url match and the second block executes for the bottom url
def fill_survey(request, unique_url, new_name="blank"):
"""
get file or redirect to error page
"""
if len(unique_url) < 50:
if unique_url == "new":
firstlast = new_name.split(" ")
c = Client.objects.get(firstname=firstlast[0], lastname=firstlast[1])
survey_url_number = generate_survey(request, c.email)
response = Survey.objects.get(number=survey_url_number['number'])
return render(request, 'survey/survey.html', {'survey': response})
else:
response = Survey.objects.get(number=unique_url)
return render(request, 'survey/survey.html', {'survey': response})
The rendered page then has the following static paths for the first and second url match respectively:
wwww.mysite.com/static/etc...
www.mysite.com/module_name/static/etc...
Paths in my template like:
<link rel="stylesheet" href="../../../static/classic/global/css/bootstrap.min.css">
Why are these different URLs leading to different static paths?
Thanks in advance!
Here's the relevant docs but by default Django only looks for static resources in /static/ folder or its subfolders. You can define a list of static file directories in your settings file if you want though.
https://docs.djangoproject.com/en/2.0/howto/static-files/
EDIT: Response to comment.
Can I see your template? Also, I'd try changing all your urls to end in a /$.
EDIT: Response to posted template.
I use the static tag rather than the absolute. I.E.
<link rel="stylesheet" href="{% static "/css/bootstrap-3.3.7.min.css" %}">
This way if we mess with the location of our templates we don't ned to go back and change all the templates
.
A couple thought about your html:
Since it doesn't start with / it's pointing to the a folder within the current folder.
With a / it points to the path at the root of your current web.
See https://www.w3schools.com/html/html_filepaths.asp
Regarding why I end my addresses in /$. Here's a good answer.
Why django urls end with a slash?
I wish I had a clearer answer for you but try the trailing / in the url and the leading / or {% static %} in your template.
So I've been hitting my head against the wall on this for the last hour and can't seem to figure out why none of the static media (CSS, Images, JS etc) when my template is rendered.
Could someone please help me find out why adjustments I need to make? Below are snippets from Settings.py, Index.html and stylesheet please let me know if more is needed.
My static files are located in the following directory:
/djangoproject/website/static
Settings.py - Located /djangoproject/djangoprojectname/
STATIC_ROOT = os.path.normpath(os.path.join(PROJECT_ROOT,
"/static/"))
STATIC_URL = '../website/static/'
Here's a snippet from my index.html that is supposed to be calling the css style sheet with {{ STATIC_URL }}
Index.html - Location /djangoproject/website/templates/
<link rel="stylesheet" href="{{ STATIC_URL }}css/style.css">
Location of CSS StyleSheet
style.css - Location /djangoproject/website/static/css/
From the Django docs:
If {{ STATIC_URL }} isn't working in your template, you're probably
not using RequestContext when rendering the template.
As a brief refresher, context processors add variables into the
contexts of every template. However, context processors require that
you use RequestContext when rendering templates. This happens
automatically if you're using a generic view, but in views written by
hand you'll need to explicitly use RequestContext To see how that
works, and to read more details, check out Subclassing Context:RequestContext.
It seems to me that you are setting STATIC_URL to a path, when it should be set to, well, a URL. You need to set this to the web address of the folder that contains your css files, for example:
STATIC_URL = 'http://mydomain.com/static_files/'
Try to find your CSS file online by typing the address you expect it to be into your browser. Once you find the CSS file this way, just copy the root URL that got you there.
I need to server static files in my Django project.
I would like to place them in /static directory and be able to reference them in my templates.
I've been reading "Managing static files" in the documentation and I am confused. I've followed the instructions but am not able to get it to work.
1) I have put my static files in /static under each app in my project.
2) django.contrib.staticfiles is included under my INSTALLED_APPS.
I've set the following variables in settings:
STATIC_ROOT = '/static/'
STATIC_URL = '/static/'
In my template I have the following line:
<script type="text/javascript" src={{ STATIC_URL }}/a_ajax.js></script>
however when I bring up the page and look at source the line is:
<script type="text/javascript" src=/a_ajax.js></script>
It seems like nothing was passed to the template.
What am I doing wrong?
Considering that you are using Django 1.4 or higher, here is my explanation:
In Django 1.3 the static files were separated from the uploaded files (media) and now, they have their own home.
To serve static files (css, js, images, etc) in the development environment you need:
Put these files in their respective app's static subdirectory
Make sure you have django.contrib.staticfiles.finders.AppDirectoriesFinder in your settings.py (this is the default behavior)
The directory structure will be:
__| project_root/
____| your_app/
______| static/
________| test.css
________| some.js
So the request to http://localhost:8000/static/test.css will be routed to your_app/static/test.css.
Note that you don't need to change STATIC_ROOT setting, until you go to production environment that you will need to run ./manage.py collectstatic.
The collectstatic command will collect files from the app's static subdirectories and put them all in an unique place (the directory defined in STATIC_ROOT)
If you are going to deploy your project in production, see ./manage.py collectstatic documentation.
Include 'django.core.context_processors.static' is in your TEMPLATE_CONTEXT_PROCESSORS var in settings.py.
see documentation: Referring to static files in templates
Update:
And in the view, use the RequestContext object instead of the Context object.
def view1(request):
...
context = RequestContext(...
return render_to_response( ... , context )
In newer versions of Django, this is how I link to static files in a html template:
<script type="text/javascript" src="{% static 'admin/js/labeler.js' %}"> </script>
Django docs on STATIC are here:
https://docs.djangoproject.com/en/1.9/howto/static-files/
When this one runs everything goes fine:
(r"^newobject$", "views.myobjects.newobject"),
All the CSS + JS files are properly fetched from:
static/css/...
static/js/...
When this one runs:
(r"^mybjects/(([a-z]|[A-Z]|[0-9])+)$","views.myobjects.loadobject"),
All the css and JS files that are being fetched, are run trough the urlpatterns and are returning my defailt page:
(r"", 'views.main.index'),
This makes all my CSS and JS code to actualy be HTML. My guess is that i'm giving some noob mistake. Is there any common reason why this should happen? And how to fix it?
Edit:
Css example:
<link href="static/css/style.css" type="text/css" rel="stylesheet">
JS example:
<script src="static/js/libs/date.js" type="text/javascript"></script>
See the difference:
when you access *some url*/newobject the static/css/style.css refers *some url*/static/css/style.css*
when you access *some url*/newobject/whatever the static/css/style.css refers *some url*/newobject/static/css/style.css*
If your URL will always be floating around in depth, include your javascript and CSS using URLs relative to the server root (start them by /) instead of relative to the current dir.