How to use autoescape off AND static variables inside django template - python

I'm using auto generated HTML which has been saved to a file and then read in again to use as part of a page in a django template.
In order to do this I have used:
{% autoescape off %}
{{ my_html }}
{% endautoescape %}
However, in the my_html variable, I have some static content. This comes in the form of something like this:
<img src="{% static "img/tree_report.png" %}" width="12px" height="12px"/>
My issue is that the static content is not displayed. I get:
http://127.0.0.1:8000/%7B%%20static 404 (in the browser error report)
I read something about get_static_prefix in another question but that doesn't solve my problem because I just get this instead:
GET http://127.0.0.1:8000/%7B%%20get_static_prefix%20%%7Dimg/tree_report.png 404 (Not Found)
I also tried endautoscape turning on and off periodically in my_html in the saved HTML variable. That also didn't work.
Should I be autogenerating the development and production static files paths for my_html or is there a more elegant solution to this problem?
Any suggestions are most welcome.
Thanks.

Related

Django Chartit graph not displaying. Jquery issue?

There are about another 4-5 other posts with the same issue I have but either a.) the solution does not work for me or b.) there are no suggested solutions. I'm hoping someone can help me out with this. Using Chartit and looks like I am passing my object's data properly and I've got my template hitting all the necessary JavaScripts finally and now I am getting this issue from the console:
VM49842 chartloader.js:3 Uncaught ReferenceError: $ is not defined at VM49842 chartloader.js:3
highcharts.js:10 Uncaught Error: Highcharts error #13: www.highcharts.com/errors/13
at Object.a.error (highcharts.js:10)
at a.Chart.getContainer (highcharts.js:250)
at a.Chart.firstRender (highcharts.js:265)
at a.Chart.<anonymous> (highcharts.js:241)
at a.fireEvent (highcharts.js:30)
at a.Chart.init (highcharts.js:240)
at a.Chart.getArgs (highcharts.js:239)
at new a.Chart (highcharts.js:239)
at Object.<anonymous> (VM49842 chartloader.js:5)
at Function.each (jquery.1.7.2.min.js:2)
Here is the line in reference to chartloader.js line 3:
$(document).ready(function()
I've read that it could possibly be interfering with other scripts but I've got no other javascript on my Django project besides what's included in the admin portal.
Settings.py has 'chartit' in installed apps and because I've also heard that scripts could be loading slower than expected from https I've installed them all locally in my static directory and I've run 'python manage.py collectstatic' to install/move them to the proper static directory.
If it's possibly my model's information I can share that if necessary but if I view source it seems to be passing the correct information successfully.
Template - history_graph.html
{% load static %}
{% load chartit %}
{{ graph_display|load_charts:'container' }}
<script type ="text/javascript" src ="/static/js/jquery.1.7.2.min.js"></script>
<script type ="text/javascript" src="/static/js/highcharts.js"></script>
<div class='container'>{{ graph_display|load_charts:'container' }}</div>
The script references needed to be placed in front of the chartit load variable (not the highcharts script reference as previously answered in other questions). Here is the working arrangement:
{% load static %}
<script type ="text/javascript" src ="/static/js/jquery.1.7.2.min.js"> </script>
<script type ="text/javascript" src="/static/js/highcharts.js"></script>
{% load chartit %}
{{ graph_display|load_charts:'container' }}
This cleared the error for chartloader/jquery error where jquery was loading after chartit. IMO this isn't clearly stated and/or stated at all in the documentation. I was still receiving an error for highcharts though until I noticed that:
<div class='container'>
should instead be:
<div id='container'>

How to make a pdf link in Django

I'm extremely new to Django and I was hoping someone could help me add a link to my website which allows someone to download a pdf file. The pdf file is located here:
static/files/offline_reg_form.pdf
and I have no idea what the URL should be in the urls.py file or the view in the views.py file. I have looked around but nothing is working as I want it too.
Any help would be great, thanks!
For you specifically:
{% load static %}
my pdf
This will answer your questions.
https://docs.djangoproject.com/en/1.10/howto/static-files/
If it still confuses you,
{% load static %}
<img src="{% static "my_app/example.jpg" %}" alt="My image"/>
is an example of what should be in your template.

What's the difference between template include and static include in Django?

I'm trying to learn Django at the moment and am trying to make sure I'm not doing anything stupid.
I'm in the process of making my web page more modular in the sense that I am removing hardcoded values in the template (base .html). Doing so, I'm trying to convert hardcoded CDN references (jquery, bootstrap, etc.) to modular pieces that can be included in every web page. Doing so will allow me to change a single file in the future, instead of being forced to go to every web page and make that change.
However, I'm slightly confused. I'm trying to determine if it would make sense to copy them into a html file and use Django's {% include '' %} template tag to directly include the cdn portions, or if using Django's static include would be more appropriate.
So what exactly is the best route? It seems like it would be very easy to use template includes for everything static in all honesty. Why not use it to include javascript or css?
Websites generally need to serve additional files such as images, JavaScript, or CSS. In Django, we refer to these files as “static files”.
We call them 'static' simply because they aren't dynamic i.e the contents of these files are relatively fixed, either by design or by it's intrinsic characteristics (eg: binary content like images) and thus does not need to processed by our application server.
We differentiate them from other files because it's advisable to serve these static files at a lower level, for example, using nginx. This allows us to serve these files faster as is which leads to performance gains. It also allows easy caching.
But when using a CDN, you offload this work from your server to somebody else's server.
Now coming back to your question. You shouldn't have to declare your resources in every template. Usually, base.html contains the base of the page which can then me extended (read: template inheritance) by more specific (children) templates.
To understand this quickly, here's an example:
base.html:
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="~~CDN HERE~~">
<script src="~~CDN HERE~~"></script>
</head>
<body>
{% block body %}{% endblock %}
</body>
</html>
article.html
{% extends "app/base.html" %}
{% load static %}
{% block body %}
<h1>{{ page_title }}</h1>
<img src="{% static 'app/img/detective.png' %}" alt="detective" />
{{ page_content | safe }}
{% endblock %}
Now for every article on your site, you render the article template which automatically extends the base removing the need to mention your css/js files for multiple pages.
If you're using different resource files for different pages, you can creation an additional block like {% block css %}{% endblock %}
and then add this to your article.html
{% block css %}
<link rel="stylesheet" href="{% static 'app/css/article.css' %}">
{% endblock %}
Notice how I'm using static for image, which is served directly by nginx.
Theoretically, you can club your CDN links into a file and then include it in base.html, but it just leads over modularity which causes redundant complexity.
Let me know if you have any issues!

Django Get absolute url for static files

In Django, when I use:
{{ request.build_absolute_uri }}{% static "img/myimage.jpg" %}
It produces: 'http://myurl.com//static/img/myimage.jpg'. This produces an error.
How can I remove the double slashes?
The STATIC URL is:
STATIC_URL = '/static/'
But I don't think removing the first '/' would be a good idea.
The request object is available within your templates and you can easily access attributes such as request.scheme or request.META.HTTP_HOST to construct your base URL that you can prepend ahead of your static URL to get the full URL.
Final example would look something like this:
<img src="{{request.scheme}}://{{request.META.HTTP_HOST}}{% static 'img/myimage.jpg' %}">
The build_absolute_uri method builds an absolute uri for the current page. That means that if you're on e.g. 'http://myurl.com/login/', the resulted full url would be 'http://myurl.com/login//static/img/myimage.jpg'.
Instead, use request.get_host() (optionally together with request.scheme for the url scheme), or preferably, use the sites framework to set a template variable to the current site domain. The get_host() method has some issues regarding proxies.
The get_host() method will return the current domain without a path appended.
I just made a quick template tag for doing this. Create files /myapp/templatetags/__init__.py and /myapp/templatetags/my_tag_library.py, if you don't have them already, and add the following to my_tag_library.py:
from django import template
from django.templatetags import static
register = template.Library()
class FullStaticNode(static.StaticNode):
def url(self, context):
request = context['request']
return request.build_absolute_uri(super().url(context))
#register.tag('fullstatic')
def do_static(parser, token):
return FullStaticNode.handle_token(parser, token)
Then in your templates, just {% load my_tag_library %} and use e.g. {% fullstatic my_image.jpg %}.
In response to earlier comments wondering why someone would need to do this, my particular use case was that I wanted to put a link to a static file inside of an open graph protocol meta tag, and those links need to be absolute. In development the static files get served locally, but in production they get served remotely, so I couldn't just prepend the host to get the full url.
Is this worth an update (Django 2+)?
This helped me specifically because I was trying to put a query in the link, i.e. the myimage.jpg was actually pulling from the DB. I needed a way to put it in the src, which was to replace 'myimage.jpg' with {{ img_link_field_in_model }}.
<img src="{% get_static_prefix %}img/myimage.jpg">
will produce:
<img src="/static/img/myimage.jpg">
The example of the query is:
<img src="{% get_static_prefix %}img/{{img_link_from_model}}">
Use this for apps:
{{ request.build_absolute_uri|slice:":-1" }}{% static "img/myimage.jpg" %}
Use this generally:
{{ request.scheme }}://{{ request.META.HTTP_HOST }}{% static "img/myimage.jpg" %}
Not entirely sure what you're asking, but since the {% static .. %} is only adding /static/ to the front of your path you specify, you could just do that yourself:
{{ request.build_absolute_uri }}static/img/myimage.jpg
Not very modular, but then again most times you don't need direct access to the full url since it will just append it onto whatever url you're at if you use it as a src for some html object.
build_absolute_uri takes the location as an argument which handles the double slash problem.
Unfortunately you cannot pass arguments via the django template language.
You will need to build a custom template tag or filter which accepts an argument to the build_absolute_uri function.
One of the many reasons I prefer Jinja as I can just do this:
{{ request.build_absolute_uri(static('img/foo.png')) }}

load static file with variable name in django

I'm trying to do load the following static file
img file
where image is in a for loop of images derived from a database.
But I simply got an error Could not parse the remainder: '{{' from ''static/matrices/'{{'
What should I do to fix this? I can't use relative paths because this will be used by subsections as well, with the same html template.
You should pass a full string to the static tag from staticfiles. This is so it can use your staticstorages to find your file.
{% load staticfiles %}
{% with 'images/'|add:image.title|add:'.png' as image_static %}
{% static image_static %}
{% endwith %}
But in your use case it might be better if you just store the path of the images on the image model itself.
I got this to work by using an empty string for the static path and then using my variables in their own section, like this:
<a href= "{% static "" %}{{obj.a}}/{{obj.b}}/{{obj.c}}.gz" >Name</a>
You can use get_static_prefix template tag. get_static_prefix is a variable that contains the path specified in your STATIC_URL. Your code would be:
{% load static %}
img file
or
{% load static %}
{% get_static_prefix as STATIC_PREFIX %}
img file
Reference: get_static_prefix
You should avoid nesting tags.
What are you trying to solve? Isn't the image part of dynamic content? The static tag is for static content not uploaded media files.
If you must use the static tag the correct way would be something in the order of;
{% static image %} or {% static image.file %}
Depending on the object layout. If you're using an ImageField (inherits FileField) the image object already holds the path, so there's no need to manually add extensions.
What I ended up doing was to just split the path from the name itself. Those images represents tabs, are static and in a sequence. They are not connected to the database imagewise.
I didn´t want to repeat the html for every run so I ended up doing a forloop like this, a bit simplified.
{% for option in options_obj %}
<img class="highlight" src="{% static "store/img/editor/tab-" %}
{{ option.name.lower }}-selected.png">
{% endfor %}
EDIT:
Even though this does work in most situations it can really mess stuff up as well. For me this occured when having different images for different language settings and at the same time using tools like CachedStaticFilesStorage. If you need to add language code or something else to your image this is a more solid solution
{% for option in options_obj %}
<img class="highlight" src="{% static "store/img/editor/tab-"
|add:LANGUAGE_CODE|add:"-selected.png" %}">
{% endfor %}
Too many quotes!
Just
img file
and you don't have to call the static in the link because you already load the static

Categories

Resources