Using Django urls in javascript files - django

I am trying to use url-names in my javascript/jquery files for AJAX requests and I have found several solutions that can solve this problem. The one that I am currently using is the following.
I define a url to serve javascript files:
urls.py
url(r'^js/([\w\.\-]+)/([\w\.\-]+)/$', 'views.get_javascript_file', name='get_javascript_file')
url(r'^getmoredicus/$', 'load_discussions', name="load-discus"),
Then I define the view that renders the javascript files.
views.py:
def get_javascript_file(request, app_name, js_file):
'''
Used to request and serve rendered javascript/jquery files.
'''
return render_to_response("%s/%s.js" % (app_name, js_file),
context_instance=RequestContext(request))
Now in the html files, we can use the get_javascript_file url to get the rendered javascript files.
html files:
<script type="text/javascript" src="{% url get_javascript_file 'myapp' 'jsfile' %}"></script>
Now in any javascript file, I can access the url-names through {% url url-name %}.
Questions:
1) Is there a better/faster way to use url-names in javascript files? I know that there are some apps already created to accomplish this but I want to get everyone's(django experts) opinion on the best way to accomplish this.
2) Can we cache the rendered javascript files after they have been rendered the first time so that in each subsequent request, we don't have to render them again? If yes, then how can we go about doing that.
3) In this method, we are rendering the script files from their apps folders. Is there a way to access the static files located in STATIC_ROOT from the get_javascript_file view? I am just thinking about how this would work in a production environment. Is it a good practice to access static files from their apps folders rather than putting them in STATIC_URL and accessing them from there?
NOTE
I know that there are already some questions on SO that answer some parts of this question, but I just wanted to get to the bottom of this once and for all for future django learners. What is the best way to use url-names in javascript or any script for that matter?

I'm not a fan of running external js through the view rendering. Especially if you're using something like django-compressor to compress and cache your js files.
I prefer to just include the variables in a script tag prior to including the external files.
<script>
my_var = "{{ MY_PROPERTY }}"
</script>
<script type="text/javascript" src="{{ STATIC_URL }}js/external_script.js"></script>
That solution is also not always ideal, but I'm open to other solutions.

Related

Serving static images on django application?

I am have been having troubles figuring out how to serve static images with my django application. However, I have figured out a sort of "hack" to get it working but it doesn't allow for much flexibility.
In the html files I have tried the following...
<img src="{{ STATIC_URL }}textchange/nextarrow.png" class="foobar" id="foobar">
Above: The pages will load when I use this but the images will not work.
<img src="{% static "textchange/nextarrow.png" %}" class="foobar" id="foobar">
Above: The pages will not load, I get a server error
<img src="thefullurltoS3bucket/nextarrow.png" class="foobar" id="foobar">
Above: The images will load fine
I have been trying all these different formats when going to production with Heroku and S3. The question I have is is the way I'm serving my static images correct? I use the last example in which I make the src the full url to the bucket at s3. Is that fine?
It should be noted that when I use the static tag serving css files works fine. Images is the only problem.
Your first and second solutions ( that you got server error and not loading ) is the correct way of using static files which is:
<img src="{% static "textchange/nextarrow.png" %}" class="foobar" id="foobar">
review your settings.py file and set STATIC_URL and STATIC_DIRS and also STATIC_ROOT, if you got server error maybe you set the STATIC_URL or STATIC_DIRS wrong. you can find plenty of posts about these settings.
Also check your image url in browser ( sth like 127.0.0.1:8000/static/files/etc.jpg )see if you can access the image.
Serving static files in Django can be a pain.
First, make sure you use the static template tag correctly in your template:
{% load static from staticfiles %}
<img src="{% static 'path/to/image.jpg' %}">
In your settings, have your STATIC_URL point to something like '/static/', your STATIC_ROOT point to the directory where you'll actually serve your files post-collectstatic, and your STATIC_DIRS to where you'll place your static files within your project (i.e. 'static' directory).
If you're serving from S3, you'll probably follow a tutorial like this one.

Custom image in Django template via static

I am programming a website powered by Django 1.6.3. Under news you always see a big story and on the side recent articles. Therefore, I used Bootstrap 3 and wrote a static html page serving my requirements.
Now I would like to program the logic behind this. I save all my files under static that consists of the folders css, fonts (from Bootstrap), img and js. The image folder has some subfolder e.g. news. To create a new entry on the news page I would like to open the admin page, add a news_entry and select one image that should be under the titel. How is it possible to include the image in the page? My approach was:
<img src="{% static {{ news.image_name }} %}" class="img-title">
Unfortunately I get an parsing error. Image_name is a property of my news model.
You need to access the url attribute of your image_name.
Try:
<img src="{{ news.image_name.url }}" class="img-title">
Similar question here.

Static URL in JavaScript

I have a CSS file which is being used in my template file
<link href="{% static "assets/style/reset.css" %}" rel="stylesheet" type="text/css"/>
I want to access the 'static' in my JavaScript. Is it possible? How can I do it?
Your javascript has to pass through django's template redering. You could do this by rendering your javacript inside of your template like Django Template Variables and Javascript suggests.
Or you could create a view that just renders your javascript dynamically:
(r'^dynamic.js$', dynamic_js)
def dynamic_js(request):
"""
Create a js file dynamically
"""
return render(request, 'dynamic.js',
content_type='application/javascript')
# dynamic.js
# can use template tags now!
Having django serve your static assests is extremely inneffiecient, and is one of the first things to migrate away from if you want a speedy site. If your js file is rarely changing it might be better to create some sort of build process where you can generate your dynamic js with django (so you can use the template variables) and save it to you static folder, so that your webserver can serve the content for you!

django-admin and static files

I'm new to django and recently I'm following this tutorial
to write a todo-list app.
In part 2 I should customize the admin's change_list template and add an image into it.
At first I use
<img class='btn' src='static/img/on.png'>
but it turns out to be invalid.
Can anybody figure out what's the problem is? Thanks a lot.
Here is my folder structure
todo-list
todo-app
img
----on.png
----off.png
templates
admin
----change_list.html
todo-list
you can't access the static file( images, css, js ) directly in django
to serve the static files you need to use {{ MEDIA_URL }} or {{STATIC_URL}} for that How do I include image files in Django templates?, and this link
this will helps u :)

Django CSS & Static Media Not Loading

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.