Django template substitution in include JS scripts - django

I've got a javascript widget written for my Django project, which is included at the top of my templates.
<script src="{{ STATIC_URL }}/js/widget.js"></script>
The widget needs to load its own stylesheet, but since it's not actually a Django template, it doesn't know where the static root is. Does it need find its .css relative to itself, or is there a way for Django to tell it about {{ STATIC_URL }}?

You can either do relative URLs in your Javascript, which is probably preferable, or you can define a global variable:
<script>var static_url = '{{ STATIC_URL }}';</script>
<script src="{{ STATIC_URL }}/js/widget.js"></script>
Then, you can use static_url anywhere in your JS code.

I would create the STATIC_URL variable in your settings.py file, making it accessible on your entire site.
STATIC_URL = 'https://your.js.server'

Related

Cannot load static files in django

I added the following lines in my settings.py file:
STATIC_URL = '/static/'
STATICFILES_DIR = [
os.path.join(BASE_DIR,"static"),
]
STATIC_ROOT = os.path.join(BASE_DIR,"static")
Then I edited my HTML file to use {% load static %} and <img src="{% static 'static/myapp/images/ABC.png' %}" alt="">, but still I am not able to see the ABC.png pic on my webpage. Can someone please help?
Screenshots of .py files:
The issus is that you are incorrectly requesting the asset, use {% static 'myapp/images/ABC.png' %} instead. I suppose that you have the following structure in your app:
myapp
static
myapp
images
ABC.png
templetes
views.py
...
As you can see, is not necessary to add the name of your statics directory. The path is relative to the static folder of any of your apps in your project.

What is the difference between these two methods of serving static files in Django?

I have a Django app that uses different static files such as images, css files, and js files. That being said, the documentation https://docs.djangoproject.com/en/2.2/howto/static-files/ shows two different ways to serve static files, and I've also seen developers follow both methods.
I'm currently doing it like this:
#settings.py
STATIC_URL = '/static/'
# whatever.html
{% load static %}
<img src="{% static "my_app/example.jpg" %}" alt="My image">
With all my images inside the same folder as my main.css file.
But I've also seen developers following the second method of the documentation:
#settings.py
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
#urls.py
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ... the rest of your URLconf goes here ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
When using the second method, they'll have a different folder called media that is located at the same level as all main apps. Supposedly I'd leave my images in there.
I'm wondering if it's okay to follow the first method (using {% load static %}) which is what I'm doing, and what the difference between the two methods is.
Thank you!
Actually Django doesn't consider both as static files.
Static Files Images
<img src="{% static "my_app/example.jpg" %}" alt="My image">
These are the application media files and are supposed to be used in the application wide scope. They are particularly meant to be used in css, js etc.
Media Files Images
urlpatterns = [
# ... the rest of your URLconf goes here ...
]
These media files are for user-uploaded content. It particularly deals with the request response cycle.
Note:
Django disentangles user uploaded media from application media, thus making deployment, backups, and version control easier.

How to use a remote static file server while developing with django manage.py runserver

Background: I'm using the Django manage.py runserver for local development. I have the contrib.staticfiles in installed apps and I'm using its {% static %} template tag in my templates.
What I try to achieve: For development, I'd like to use an independent server for serving the static files but use the django development server to serve the Django app. So that I could access the page locally on my computer at http://127.0.0.1:8000, but all the static files would be served from another computer or from a different server on the localhost, as defined by the settings.STATIC_URL variable.
The problem: The settings.STATIC_URL variable is somehow overridden when I'm using the development server. So all my static files are served by the local django development server instead of what I defined in settings.STATIC_URL.
Solution: See Daniel's answer below!
settings.py:
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATIC_ROOT = os.path.join(BASE_DIR, 'static/')
STATIC_URL = os.path.join('127.0.0.1:666', BASE_DIR, 'static/')
example_template.html:
{% load staticfiles %}
{% load bootstrap3 %}
{% bootstrap_css %}
{% bootstrap_javascript jquery=True%}
{% bootstrap_messages %}
{# Load MyApp CSS #}
<link href='http://fonts.googleapis.com/css?family=Open+Sans:400,700subset=greek-ext,vietnamese,cyrillic-ext,latin-ext' rel='stylesheet' type='text/css'>
<link href="{% static 'css/my_app.main.css' %}" rel="stylesheet">
page source when using a browser:
<link href="FULL_PATH_TO_BASE_DIR_HERE/static/css/my_app.main.css" rel="stylesheet">
but expected to see:
<link href="127.0.0.1:666/FULL_PATH_TO_BASE_DIR_HERE/static/css/my_app.main.css" rel="stylesheet">
This isn't anything to do with Django or runserver. It's simply because you are using os.path.join() to join a domain and a path; that function doesn't know about URLs, and will assume that since BASE_DIR starts with a leading slash, it should normalize the whole path to start from there and ignore anything previous:
>>> os.path.join('127.0.0.1', '/foo', 'static')
'/foo/static'
The solution is twofold: don't use os.path.join on URLs, but more importantly, don't use BASE_DIR in your STATIC_URL. The filesystem directory your static files live in has nothing whatsoever to do with the URL they are exposed on. Your STATIC_URL should be something like "http://127.0.0.1:666/static/".

Managing static/images in Django with AppEngine

I am trying to add an image to my simple google app engine code, but it doesn't work if I follow the tutorial. It works if my image is in my app directory, but not when I move it to static.
When I am using it in plain html like:
<img src="../static/myimage.jpg"></img>
or
 
and many other variations, the image just does not show (it shows when it is outside of static dir). When I am doing it as in the tutorial, defining STATIC_URL in my settings file:
STATIC_URL = '/static/'
And adding this lines (or variations like "/my_image.jpg" and so on)
{% load staticfiles %}
<img src="{% static "my-app/myimage.jpg" %}" alt="My image"/>
causes server error (500). I am using django 1.3
Here is the directory structure:
my-app
\static
myimage.jpg
\templates
base.html
# and other html files
\urls.py, settings.py #and other .py files
App.yaml:
-url: /(.*\.(gif|png|jpg))
static_files: static/\1
upload: static/(.*\.(gif|png|jpg))
setting.py:
ROOT_URLCONF = 'urls'
urls.py:
STATIC_URL = '/static/'
What did you set STATIC_ROOT to?
Generally though, using GAE's static file handlers in app.yaml will give you better caching and probably lower cost than serving the images with django's staticfiles.

Django - Displaying video with jwplayer

I am currently trying to display a video on a website using jwplayer. The view for the page is
def video(request):
return render_to_response('video_player/video.html', context_instance=RequestContext(request)
And the html template being used contains this in the head:
<script type="text/javascript" src="/jwplayer/jwplayer.js"></script>
And this in the body:
<div id="myElement">Loading the player...</div>
<script type="text/javascript">
jwplayer("myElement").setup({
file: "{{ MEDIA }}videos/test.mp4",
image: "{{ MEDIA }}videos/cute-bunny.jpg"
});
</script>
It doesn't display anything other than 'Loading the player', i think there may be something wrong with me calling the media_root. It is defined as:
MEDIA_ROOT = 'C:/Users/Timmy/Documents/GitHub/GroupProject/media'
You should be using the {{ MEDIA_URL }} tag in your templates, which you define in settings.py.
Example in settings.py:
MEDIA_URL = '/media/'
MEDIA_ROOT, like STATIC_ROOT, is the directory that Django uses to upload media files to and serve media files from, not the URL path.
See: https://docs.djangoproject.com/en/dev/howto/static-files/#serving-files-uploaded-by-a-user