Feeding image to a Django template - django

I've been working on a simple Django project for myself and I came into a little problem.
When first developing the blog, I didn't make templates, I just made sure things were working properly, but now, I dived into making the templates and everything is working besides my header background-image.
Before the templates, I was doing it like this:
<header class="masthead" style="background-image: url({% static 'img/home-tech-bg.jpg' %})">
This was working just fine, but now that I'm trying to do the same as a template it doesn't work. It doesn't return me any errors, but the image doesn't display.
What I did was the following:
template base.html
<header class="masthead" style="background-image: url({% block headerimage %} {% endblock %})">
blog.html
{% load static %}
{% block headerimage %}
{% static 'image/image.jpg' %}
{% endblock %}
What is a better way to do this?

Well first off move your static directory to your root directory and write the path in the template like this:
{% load static %}
<img src="{% static 'img/home-tech-bg.jpg' %}" alt="/">
Also make sure your settings.py file is properly configured to serve static files, add this line if you havent yet:
STATIC_URL = '/static/'

Related

loading an image using the static tag from a static path

I am unable to load an image on my index page using the following syntax
{% extends "base.html" %}
{% load crispy_forms_tags %}
{% block content %}
<-!---This is the statement-->
<-div data-src= "{% static "bootstrap/images/slider/slider-img1.jpg" %}">
<-/div>
{% endblock content %}
I added an extra - (dash) in the div because the post had difficulty displaying it.
Anyways I am getting the error
Invalid block tag on line 69: 'static', expected 'endblock'. Did you forget to register or load this tag?
I think this is a directory structure. My directory currently looks like this
|_mainApp
| |_______index.html ------>This is where i am trying to run the statement
|_templates
| |_______base.html ------->The statement works fine in the base
|_static
|_bootstrap
|_CenterApp
|_settings.py
|_urls.py
Any suggestions on why I am getting that error is that a location issue and the content cant be found ? or is it something else ?
use
{% load staticfiles %}
below you have extended your base.html
In django template it is important to call {% load staticfiles %} whenever you are using static in template. More details here
Whenever you use {% extend "some_page.html" %} and you need some links with static url you can use {{STATIC_URL}} instead of {% static "/some/link/" %}
So in your case, use it as:
<-div data-src= "{{STATIC_URL}}bootstrap/images/slider/slider-img1.jpg">

Django how to dynamically add js and CSS in sub templates?

I am new to Django.
I have a basic template set up where I have base.html using {% block body %}{% endblock %} to include a sub template of index.html and test.html where they have {% extends 'base.html' %} at the top.
The base.html template includes Bootstrap. It is where the CSS and JS are included. index.html needs to include select2 but test.html does not.
I could use blocks here to solve my problem (adding CSS and JS block to base.html) but I see that as getting very messy very quickly.
Is there anyway I can use assets in Django to create a select2 asset and have that called in the sub template to register the needed JS and CSS with the parent template?
All I see is compression and numerous searches have, so far, come up empty.
It okay to add 2 more blocks in your base.html:
<some css>
{% block additional_css %}
{% endblock additional_css %}
...
<some js>
{% block additional_js %}
{% endblock additional_js %}
and the override them in any page extended from base.html:
{% extends "base.html" %}
{% block additional_css %}
<link rel="stylesheet" type="text/css" href="{% static 'css/bootstrap-datetimepicker.min.css' %}">
{% endblock additional_css %}
...
{% block additional_js %}
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.11.0/moment.min.js"></script>
<script type="text/javascript" src="{% static 'js/bootstrap-datetimepicker.min.js' %}"></script>
{% endblock additional_js %}
That is a good practice because in this case the scripts will load in the very end and if some of your added script require for example JQuery, you won't face any problems.
It doesn't make the code messy, it's flat and easy to explain. It's better to think how not to make JS messy, and as you pointed, there are several ways to do this, on of them is to compress all the JS.
There are a few options that I can think of
The first is the ugly way that involves an {% if include_my_js_please %} in the base.html that is ignored if the context variable isn't included and for obvious reasons, arguments would be had if this made its way into our production code
The second is the way that you say can get very messy but its the way we do it and works very well for us, we have an {% extended_head %} and {% extended_footer %} in the base.html and as you'd expect we use this sparingly when required. Although we are very careful about what is included into this.
The third way is to just include everything in the base.html and only worry about it when it actually becomes a problem (I can see both the pros and con's of this)
and the fourth and final way I can think of is to make use of the Forms Media class
Django allows you to associate different files – like stylesheets and scripts – with the forms and widgets that require those assets. For example, if you want to use a calendar to render DateFields, you can define a custom Calendar widget. This widget can then be associated with the CSS and JavaScript that is required to render the calendar. When the Calendar widget is used on a form, Django is able to identify the CSS and JavaScript files that are required, and provide the list of file names in a form suitable for easy inclusion on your Web page.
Obviously this doesn't work in all use cases

Django Template short hand for loading and using static files

For example to load a static image, I need to do that in template in two lines, like this:
{% load staticfiles %}
<img src="{% static "img/pro_pic.png" %}">
Is there any way to do that in one line?
<img src="{% staticLoad( "img/pro_pic.png" ) %}">
and a function somewhere that checks {% load staticfiles %} is there or not, if not it loads and all that? I also encourage time complexity discussion if it can be done!
By default the django.core.context_processors.static context process is included in the TEMPLATE_CONTEXT_PROCESSORS setting so you can just write in your template:
<img src="{{ STATIC_URL }}img/pro_pic.png">

Resolve Static URL on Server

All of my user's have the option to link a profile picture. There are several templates that need to load this profile picture. If the user has not uploaded a picture, we use a default. When I want to display this profile picture, my code looks like this
<img src="{% if user.profile_picture.search_thumbnail.url %}{{ user.profile_picture.search_thumbnail.url }}{% else %}{% static "alternate.jpg" %}{% endif %}">
This is way too verbose for me, especially considering I need to repeat it out in multiple templates. I could use {% with %} blocks to store user.profile_picture.search_thumbnail.url, but that won't help me too much.
My solution was to write a function attached to the user model that returns the url of the static file. Unfortunately, the {% static %} is a template function. {% url %} has an equivalent function on the server called django.core.urlresolvers.reverse(). Does the alternative thing exist for the {% static %} tag?
In case anyone asks, I want to use the static function because my static files are stored in different places depending on the environment. My dev machine serves files locally, while my PRD machine serves static files from s3.
Thank you,
Nick
why not write a filter so you can do this.
<img src="{{ user.profile_picture.search_thumbnail.url|custom_filter }}">
and in the custom_filter you read from the settings.STATIC_URL to return the correct URL the user one is not set.
you could make the filter even shorter like this
<img src="{{ user|user_pic_url }}">
and in the filter pull out the .profile_picture.search_thumbnail.url /checks
This is what the static templatetag does underneath, and you can use it just fine in your own code:
from django.contrib.staticfiles.storage import staticfiles_storage
def static(path):
return staticfiles_storage.url(path)

Include css, js, html from apps in Django project, in a modular way

I have django project with several apps. In my main html template I am including the relevant resources -- js, css in this case and those entries are coded in by hand like so:
<script src="{% static 'js/test.js' %}"></script>
I'd like to modularize this so that I can somehow loop over my projects and have their dependencies included only if they are installed/enabled. In this way I can also add more apps in the future and not have to touch my main template.
Is there an elegant way to accomplish this?
My thought is that if I can pass each application's required resources to the main template as parameters via views.py then maybe I can loop over them (utilizing sekizai...):
{# Include external app resources #}
{% for app, template in installed_apps.items %}
{% include template %}
{% endfor %}
And views.py would go something like:
external_apps = [foo, bar]
external_apps = settings.EXTERNAL_APPS # Ok, this should exist in settings already
def main(request):
installed_apps = {}
for app in external_apps:
installed_apps[app] = app + "_template.html"
template = loader.get_template('main_template.html')
context = RequestContext(request, {
'installed_apps': installed_apps,
})
return HttpResponse(template.render(context))
Then for each app I would create a template that would fill out the necessary blocks in the main template file.
This approach seems pretty rigid though and I'm wondering if there is a more common or standardized way to go about this.
base.html:
...
<script src="{% static 'js/test.js' %}"></script>
{% block extra_js %}{% endblock extrajs %}
...
In your app template:
{% block extra_js %}<script src="{% static 'js/myapp.js' %}"></script>{% endblock extra_js %}