I am attempting to create a static link to an html file that I will load into an <a> tag or an <iframe>. Here is how I create the url:
{% with '/static/projects/'|add:project.slug|add:'/'|add:f|add:'.html' as banner_static %}
{% static banner_static %}
{% endwith %}
This code creates the desired url (/static/projects/project-name/file-name.html), but as soon as I add this to an tag I get this:
test
Any ideas as to why it is being truncated? Am I not using the django template tag correctly?
My original plan did work, turned out I had not made sure the '{% static banner_static %}' was properly wrapped by the 'with' loop.
Related
Can I use Django's template tags inside Javascript? Like using {% form.as_p %} in jQuery to dynamically add forms to the page.
Yes, I do it frequently. Your javascript has to be served through django, but if you just have it in the html header as inline javascript you'll be fine.
E.g: I use this to put prefix on a dynamic formset I use.
{% extends "base.html" %}
{% block extrahead %}
<script type="text/javascript">
$(document).ready(function() {
{# Append fields for dynamic formset to work#}
{% for fset, cap, _, tid in study_formsets.fset_cap_tid %}
$(function() {
$('.form_container_{{ tid }}').formset({
prefix: '{{ fset.prefix }}',
formCssClass: '{{ tid }}',
extraClasses: ['myrow1', 'myrow2']
});
});
{% endfor %}
});
</script>
{% endblock %}
Note in "base.html" I have a html head where the jquery libraries are loaded, that contains {% block extrahead %}{% endblock %}.
You can't use Django's template tags from your Javascript code if that's what you mean. All the Django variables and logic stop existing after the template has been rendered and the HttpResponse has been sent to the client. At that moment when Javascript executes, the client (browser) has no notion the variables you rendered the template with (such as "form").
What you can do is have Javascript modify your HTML page using chunks of HTML that were rendered by your Django template.
If you want to generate HTML on client side, I'd recommend to look at client side tempalte libraries (eg. JQuery Templates - use those with the {% verbatim %} templatetag).
If you want to use variables inside your rendered javascript I (that's my opnion), think it's a bad idea. But if all you want is to generate URL for your views, media and static files, I do this a lot.
Take a look to this github: jscssmin
Yes, you can use`
Example : `{{ user.username }}`
Be sure this is not single quotes but '(back tick / back quote)
I'm trying to extend the password reset form like so:
<!-- templates/registration/password_reset_form.html -->
{% extends registration/password_reset_form.html %}
{% block content %}
<h1> hello </h1>
{% endblock %}
As far as I can tell, this should take the template from /usr/local/lib/python3.7/site-packages/django/contrib/admin/templates/registration/password_reset_template.html (which exists, I checked) and replace the block content with the one at templates/registration/password_reset_form.html.
But this isn't happening. In fact, there is no change, nor is there an error. What am I doing wrong?
UPDATE:
I tried deliberately introducing a syntax error into the template name, and no error was issued. It leads me to believe that the template file is not being read at all. According to the django docs, registration/password_reset_form.html is the path to the default template. Why am I not able to at least introduce an error?
Put quotes around path, like this:
{% extends "registration/password_reset_form.html" %}
{% block content %}
<h1> hello </h1>
{% endblock %}
Also if your own template file didn't read at all, make sure that you have your app in INSTALLED_APPS in settings.py and TEMPLATES has 'APP_DIRS': True or DIRS set properly.
Why don't you just use the full path to the html file then?
/usr/local/lib/python3.7/site-packages/django/contrib/admin/templates/registration/password_reset_template.html
Right now you are extending the same file you are working on
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">
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)
I'm trying to include a static html page from a django template.
I tried using {% include the_static.html %} but this doesn't work for some unknown reason.
the_static.html page is a data page that will be modified often with an html editor.
and my_model has a url to this html and include it. But django refuses to find it although I'm sure I've setup the path correctly.
You can write your custom template tag to do this.
Create a file named includestatic.py under appname/templatetags/. Also, remember to create appname/templatetags/__init__.py, to include the app in settings and to restart the server.
includestatic.py should have this code:
from django import template
from django.contrib.staticfiles import finders
from django.utils.html import escape
register = template.Library()
#register.simple_tag
def includestatic(path, encoding='UTF-8'):
file_path = finders.find(path)
with open(file_path, "r", encoding=encoding) as f:
string = f.read()
return escape(string)
To use it in your template, put {% load includestatic %} at the top of your template, and then use the tag like {% includestatic "app/file.txt" %}.
I am not sure I understand everything yet...
You've an HTML page served by Django on a given url, let's suppose it to be http://mydjangodomain/get_the_static/. This URL is set in the urls.py of your model. Ok, that's normal.
You have a django template for this model. Let's suppose it's defined in a template directory mytemplates/mymodeltemplates/ and it's called myfrontpage.html (since in Django templates are html files).
I guess you've an URL defined in your urls.py to server that front page ? Let's suppose it's http://mydjangodomain/get_the_front_page/
Now I don't understand how your front page use your static html. Do your final front page html need the static's URL for a "src" attribute or something like it, or do you need to include the static's html into the front page's html ?
In the 1st case, you already have the URL, it's http://mydjangodomain/get_the_static/ so just use it as if.
In the 2nd case, you don't need the previous URL, get ride of it. Furthermore, put the_static.html in mytemplates/mymodeltemplates/. Then you need the {% include "/mymodeltemplates/the_static.html" %} tag. If this doesn't work, make sure you've the following in your settings:
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
)
APPLI_ROOT_PATH = "<absolute_path_to_the_application_root_on_your_server>"
TEMPLATE_DIRS = (
'%s/mytemplates' % APPLI_ROOT_PATH,
)
Sort of resurrecting the dead, but at least with django 1.10, there's a very clean answer here:
http://www.effectivedjango.com/tutorial/static.html
an excerpt from that page:
Simple Template Inclusion We want to add the Boostrap CSS to all of
our templates, but we’d like to avoid repeating ourself: if we add it
to each template individually, when we want to make changes (for
example, to add another stylesheet) we have to make them to all the
files. To solve this, we’ll create a base template that the others
will inherit from.
Let’s create base.html in the templates directory of our contacts app.
{% load staticfiles %}
<html>
<head>
<link href="{% static 'bootstrap/css/bootstrap.min.css' %}"
rel="stylesheet" media="screen">
</head>
<body>
{% block content %}
{% endblock %}
<script src="{% static 'bootstrap/js/bootstrap.min.js' %}"></script>
</body>
</html>
base.html defines the common structure for our pages, and includes a
block tag, which other templates can fill in.
We’ll update contact_list.html to extend from base.html and fill in
the content block.
{% extends "base.html" %}
{% block content %}
<h1>Contacts</h1>
<ul>
{% for contact in object_list %}
<li class="contact">{{ contact }}</li>
{% endfor %}
</ul>
add contact
{% endblock %}
Having followed this exactly, I now have a base.html that includes all my style references and the navigation bars/etc, so the html in the block content is merely the central contents of each (varying) page.
Do you mean that you want to EXTENDS the parent template the_static.html?
If yes, you should add below code at the first line of your children template:
{% extends "the_static.html" %}
Details documentation can be found here