Django: include html saved as string in template rendering - django

I build an HTML table in my views.py function and I want to include it in a template that I already have when rendering. I see that the div is created, but the HTML table is not created. What is the problem?
this is the line in views.py:
render(request, 'aztracker/import_data.html', {'my_html':html_data})
where html_data is like
"<table><tr><th>column1</th></tr><tr><td>data1</td></tr> ....</table>"
and I have this section in my import_data.html:
<div class="bootstrap-iso">
<div class="tbl_container_numbers">
{{ my_html }}
</div>
</div>
this is the sanme div after rendering:
<div class="bootstrap-iso">
<div class="tbl_container_numbers">
</div>
</div>

I found the problem. To render an html code stored as a string we should use the built-in autoescape tag:
<div class="bootstrap-iso>
<div class="tbl_container_numbers">
{% autoescape off %}
{{ my_html }}
{% endautoescape %}
</div>
</div>

Related

Django Calculation inside HTML

I wanted to do something simmilar to this suing django. but somehow i it doesn't work. how do i fix it?
for statik in statistik{
print(statik*total/100)
}
Is there any documentation regarding what I'm trying to implement to my django app? Thank you
Here's the HTML :
{% if statistics %}
{% for statik in statistics|slice:":4" %}
<div class="mb-3">
<div class="small text-gray-500">{{ statik.name }}
<div class="small float-right"><b>{{ statik.voters }} of {{ total }} Voters</b></div>
</div>
<div class="progress" style="height: 12px;">
<div class="progress-bar bg-success" role="progressbar" style="width: {{ statik.voters * total/100 }}%" aria-valuenow="50"
aria-valuemin="0" aria-valuemax="100"></div>
</div>
</div>
{% endfor %}
{% else %} <p>END TABLE</p>
{% endif %}
It is recommended you do calculations of any sort in view and pass it in context.
If you still want to go this route there are no math template tags except add included so you should create custom template tags or use django-mathfilters

How can I use Django inline formset with Bootstrap-select plugin?

I've been trying to use the Django inline formset with the bootstrap-select plugin from here https://developer.snapappointments.com/bootstrap-select/ and every other thing works perfectly, I'm able to successfully call the plugin on another two selects that I have in my form and I'm using the inline formset to add new authors on my book. When i put the "selectpicker" class, it only works once, when the page is loaded, but when I press the button to add more authors, the select field is not loaded.
So I have a question... can I use the two together? If yes, how? If not, is there any workaround to be able to search in a selection field?
Bellow is a image to how my form looks when i press the big green "Add" button at the end of the form.
You can see that there is only two fields, one less than the first one.
If any code is needed, please let me know and i will add right away.
Thanks!
EDIT:
Here are my codes, as asked by Chris:
My template:
{% extends 'base.html' %}
{% load widget_tweaks %}
{% block content %}
{% load static %}
<form method="POST" class="form" action="">
{% csrf_token %}
[other fields]
...
<!-- HERE I HAVE MY TWO OTHER SELECT FIELDS WHICH WORK PERFECTLY -->
<div class="container">
<div class="col-sm-12">
<div class="form-group">
<div class="row">
<div class="col-sm-6">
<label>Editora do Livro:</label>
{{ form.editora_cod_editora|add_class:"selectpicker form-control"|attr:"data-live-search='true'" }}
</div>
<div class="col-sm-6">
<label>Categoria do Livro:</label>
{{form.categoria_cod_categoria|add_class:"selectpicker form-control"|attr:"data-live-search='true'" }}
</div>
</div>
</div>
</div>
</div>
<!-- HERE START MY ONLINE FORM, AS SHOWS THE PRINT -->
<div class="container">
<div class="col-sm-12">
<hr>
<h4>Adicionar Autor</h4>
<hr>
<div class="form-group bg-light rounded ">
{{ autor_livro.management_form }}
{% for form in autor_livro.forms %}
<div class="{% cycle 'row1' 'row2' %} formset_row m-5 inline-form">
{{ form.autor_cod_autor|add_class:"selectpicker form-control"|attr:"data-live-search='true'" }}
{{ form.ordinal_autorlivro|add_class:"form-control" }}
{{ form.autor_funcao|add_class:"form-control" }}
</div>
{% endfor %}
</div>
</div>
<div class="container">
<div class="col-sm-12">
<div class="form-group">
<div class="row">
<div class="col-sm-8"></div>
<div class="col-sm-4">
<button type="submit" class="btn-outline-primary btn float-right">Salvar</button>
</div>
</div>
</div>
</div>
</div>
</form>
{% block scripts %}
<!-- HERE I HAVE MY SCRIPT THAT MAKES THE INLINE FORM WORK WITH THAT PLUGIN -->
<script src="{% static 'js/jquery.formset.js' %}"></script>
<script type="text/javascript">
$('.formset_row').formset({
addText: 'Adicionar Autor',
deleteText: 'Remover',
prefix: 'autorlivro_set'
});
</script>
{% endblock %}
{% endblock %}
The answer is the behaviour of the bootstrap-select plugin. You are activating it by using the class "selectpicker". After loading the page some javascript magic takes the elements with the class selectpicker and creates the widget you see. The "select" you now see is not your original <select> but an auxillary widget, your <select> is still there but hidden from your view.
Now when you add another form the javascript magic is not called again, so that you get a new form where your <select> is hidden somewhere from the user's eyes.
In order to get it rendered nicely again you need to run the required javascript after you have added a new form. django-dynamic-formset provides an option called added allowing you define a function which is called after the new form has been added. Form more details see the formset options here.
So define the function and call it after adding a form. In your case your script could look like this:
<script type="text/javascript">
var activate_select = function(row){
row.find('.selectpicker').selectpicker();
};
$('.formset_row').formset({
addText: 'Adicionar Autor',
deleteText: 'Remover',
prefix: 'autorlivro_set,
added: activate_select
});
</script>

Wagtail page context in Streamfield template

I have StructBlock with it's own template, within a StreamField. I'm trying to access the page object from said template.
{% load wagtailcore_tags article_tags %}
{% article_constants as constants %}
<div id="interactions__combo__addition" class="col-md-6">
<h3>
{% include_block page.translated_title %}
+
<span id="interactions-combo-addition-temp">?</span> =
</h3>
<div alt="dangerous to synergy bar" style="height:10px; width:100%">
</div>
</div>
<div class="interactions__combo__result col-md-5">
<h3 class="interactions__combo__result__title">
{{ constants.select_element }}
</h3>
<p class="interactions__combo__result__description">
{{ constants.none_selected_text }}
{% include_block page.colour %}.
</p>
</div>
{% include_block page.colour %} and {% include_block page.translated_title %} render nothing.
Thank you in advance for your help.
You should use the {% include_block %} tag when outputting the StreamField on your page template. For example, if your StreamField is called body, use {% include_block page.body %} on your page template. This will ensure that the context variables from the outer template (including page) are available in your StructBlock's template - if you use {{ page.body }} instead, the StructBlock template will render, but won't have access to the variables from the outer template.
Don't use {% include_block %} for fields of page that are not StreamFields, such as page.translated_title.

Django 1.11: pass id to url to generate detail view

I've a list of "nanas" (babysitters) that I render correctly. Now I need that when someone clicks on one of them , a detail page (for only the clicked nana opens).
I think my problem is on my template for all the Nanas, in the href:
<a href="{% url 'app-administrador:nana' nana.id %}">
Or in the Urls.
All Nanas page:
This is listing nanas View:
class NanasView(View):
def get(self, request):
nanas = Nana.objects.all()
context = {'nanas': nanas}
return render(request, 'app_administrador/nanas-registradas.html', context)
It's URL:
url(r'^referencias_de_nanas', views.NanasReferenciasView.as_view(), name='referencias_de_nanas'),
All Nanas templates:
{% extends 'app_administrador/templates/base.html' %}
{% load staticfiles %}
{% block content %}
<!-- Member Entries -->
{% for nana in nanas %}
<!-- Single Member -->
<div class="member-entry">
<a href="extra-timeline.html" class="member-img">
<i class="entypo-forward"></i>
</a>
<div class="member-details">
<a href="{% url 'app-administrador:nana' nana.id %}">
<h4>
<p href="extra-timeline.html">{{ nana.nombre }} {{ nana.apellido_paterno }} {{ nana.apellido_materno }}</p>
{% if nana.foto %}
<img src="{{ nana.foto.url }}" class="img-rounded" width="160px"/>
{% endif %}
</h4>
<!-- Details with Icons -->
<div class="row info-list">
<div class="col-sm-4">
<i class="entypo-briefcase"></i>
<a href={{ nana.antecedentes_policiales }}>Antecedentes policiales</a>
</div>
<div class="col-sm-4">
<i class="entypo-twitter"></i>
#johnnie
</div>
<div class="col-sm-4">
<i class="entypo-facebook"></i>
fb.me/johnnie
</div>
<div class="clear"></div>
<div class="col-sm-4">
<i class="entypo-location"></i>
{{ nana.direccion }}
</div>
<div class="col-sm-4">
<i class="entypo-mail"></i>
{{ nana.correo }}
</div>
<div class="col-sm-4">
<i class="entypo-linkedin"></i>
johnkennedy
</div>
</div>
</a>
</div>
</div>
{% endfor %}
{% endblock %}
Nana's detail page:
My try on showing the detail page for clicked nana:
class NanasValidarReferenciasView(View):
def get(self, request, nana_id):
# nana_id_is = nana_id
nana = Nana.objects.get(id=nana_id)
context = {'nana': nana}
return render(request, 'app_administrador/validar-referencias-nana.html', context)
It's URL:
url(r'^nana', views.NanasValidarReferenciasView.as_view(), name='nana'),
You see your href looks like this: <a href="{% url 'app-administrador:nana' nana.id %}"> which is totally fine. This means that the url link adds the two string together into one address. I don't know exactly how your urls are set up so it could look something like this:
root_url/2
Where root_url is whatever you have and 2 is the nana.id. To pass that to the url-view, it needs to accept any integer variable. Something like this:
urls.py
url(r'^nana/(?P<nana_id>\d+)/$', views.nanas_specific, name='nana'),
The P stands for Parameter, and it uses Regex logic if you want to look that up.
Then in your views, you can have a function ready to accept the parameter:
views.py
def nanas_specific(request, nana_id):
Where nana_id contains the result from the urls parsing.
I mostly work with function based views, but I'm assuming the same logic applies to classbased views. The id is not part of the URL and hence is not passed on. Change the url to
url(r'^nana/(?P<nana_id>\d+)/$', views.NanasValidarReferenciasView.as_view(), name='nana'),

How to use array elements as labels using for loop in Template Django?

I have the following template code,presently i m getting for loop counter as label for my formset. How can i get elements of array 'month' (eg month.counter, where counter is loop) as my label?? I tried {{month.forloop.counter}} but that didnt worked
<html>
<head>
<title>Actuals</title>
</head>
<body>
<h1>Actuals Data</h1>
<h2>Your Account Number is : {{ Account_Number }}</h2>
<h2>You Chose {{ Year }} {{month}} as period.</h2>
{% if form.errors %}
<p style="color: red;">
Please correct the error{{ form.errors|pluralize }}below.</p>
{% endif %}
<form action="." >
{{ formset.management_form }}
<table>
{% for form in formset %}
{{form.id}}
<div class="field">
{{ form.Value.errors }}
<label for="id_Value">{{months}}.{{forloop.counter}}</label>
{{ form.Value }}
</div>
{% endfor %}
</table>
</form>
</body>
</html>
You can do this using custom templatetags. Sample code is given below:
add following to /{app_name}/templatetags/app_tags.py
from django import template
register = template.Library()
#register.filter
def month(value, counter):
try:
month = value[counter]
except IndexError:
month = ""
return month
put following in your template
{% load app_tags %}
............
............
{% for form in formset %}
{{form.id}}
<div class="field">
{{ form.Value.errors }}
<label for="id_Value">{{ months|counter:forloop.counter }}</label>
{{ form.Value }}
</div>
{% endfor %}
............
............
View this link, some person has also tried different methods to do this; although none of them worked. ;)
There isn't ready-made filter/tag for this in django template.
You could try writing your custom filter/tag. Refer Custom template tags and filters