increment a variable in django templates - python

All,
How Can we increment a value like the following in django templates,
{{ flag =0 }}
{% for op in options %}
{{op.choices}}<input type="radio" name="template" id="template" value="template{{flag++}}"/>
{% endfor %}
thanks..

I don't think it's intended you should alter data in your templates. For in your specific case, you could instead use the forloop.counter variable.
For example:
{% for op in options %}
{{op.choices}}<input type="radio" name="template" id="template{{forloop.counter}}" value="template{{forloop.counter}}"/>
{% endfor %}
Also note that I added that number to the id attributes of the <input /> tag. Otherwise you'll have multiple inputs with the same id.
EDIT: I didn't note that it was a radio input. You could of course have the same name for each <input type="radio" />.

You explicitly can't do that in a template. Variable assignment is not allowed.
However if all you want is a counter in your loop, you just need to use {{ forloop.counter }}.

You might also want to look into having Django forms produce these values

Related

Jinja2: how to evaluate Python variable in an if-statement? [duplicate]

I have a Jinja2 Template I'm working on for a database editing app, and I'm trying to make it 'extendible' - rather than hard-coding the editing page, I'm passing a list of attributes that I want in the table, and using a for loop to iterate over them. It works aside from one thing - in the hardcoded version, I use an attribute of an object that's being passed to see if that value has been set (they are all boolean), but I can't see how to get jinja2 to take the 'capability' and use that as an attribute of the 'pupil' object; i would have used 'eval' in Python, but can't see how to get this to work. Here's an idea of the code:
{% for capability in capability_list %}
<tr>
<td>{{ capability }}</td>
<td>
{% if pupil.capability %}
<img src="{{request.static_url('gdpr_permissions:static/tick.png')}}" width="25">
{% else %}
<img src="{{request.static_url('gdpr_permissions:static/cross.png')}}" width="25">
{% endif %}
</td>
<td>
<div class="onoffswitch">
<input type="checkbox" name="{{ capability }}" class="onoffswitch-checkbox" value ='No' id="{{ capability }}" checked>
<label class="onoffswitch-label" for="{{ capability }}">
<span class="onoffswitch-inner"></span>
<span class="onoffswitch-switch"></span>
</label>
</div>
</td>
</tr>
{% endfor %}
It's the {% if pupil.capability %} part that doesn't work - I want this to become (say) pupil.web_access and pupil.database_access etc., following the capability list which is being iterated over.
Any ideas on how to get this working with jinja2, or how else it can be approached? The other idea I had was to iterate over the current settings in the python backend and then pass a list of booleans separately, but this seems to be adding an extra level of complexity.
This is because you are passing in a string instead of an attribute. Use getattr() instead. Do something like getattr(pupil, capability)

Is there a way to dynamically set the default value of a wtform radiofield from within the html template?

I'm trying to dynamically set the value of a radio field within the HTML template but I'm not sure how to set the default selection. I want to do this because the forms I want to use are forms that can be saved and re-edited if need be, so I want the default values to be values set when previously saved/submitted.
the wtform fields
field_1 = StringField('field_1')
radio_1 = RadioField('radio_1', choices=[(1,'Yes'),(2,'No')])
what i want to be able to do is something like this:
data is database data
{% if data.field_1 = 'X' %}
{{ form.radio_1(id="radio_1",class="ff-style-radio",default=1) }}
{% else %}
{{ form.radio_1(id="radio_1",class="ff-style-radio",default=2) }}
{% endif %}
I haven't had any success trying this method, swapping default for value, etc. Is something like this possible? If not how would I separate the wtform radio field choices so I can just manually mark which selection is checked? Or should I just use the base HTML method and do something like this:
<ul class="ff-style-radio" id="radio_1">
<li>
{% if data.field_1 = 'X' %}
<input id="radio_1-0" name="radio_1" type="radio" value="Yes" checked>
{% else %}
<input id="radio_1-0" name="radio_1" type="radio" value="Yes">
{% endif %}
<label for="radio_1-0">Yes</label>
</li>
<li>
{% if data.field_1 = 'X' %}
<input id="radio_1-1" name="radio_1" type="radio" value="No">
{% else %}
<input id="radio_1-1" name="radio_1" type="radio" value="No" checked>
{% endif %}
<label for="radio_1-1">No</label>
</li>
</ul>
Thanks for any help
If you want to use the form to edit data already in your database, you should supply this data to the form at creation time in your view function. This will allow you to keep your templates simple and reusable. Data from the database can be passed to the form either as an object or as a dictionary https://wtforms.readthedocs.io/en/stable/forms.html. If your form maps directly to a database table you can just pass this unmodified from your query. In the following code I've followed your example and created a new dictionary to set the value of radio_1 based on the value of field_1.
#app.route("/myurl")
def myview():
# do database lookup here
olddata = {"radio_1": 1 if data.field_1 == "X" else 2}
form = Myform(formdata=request.form, data=olddata)
if request.method == "POST" and form.validate():
# .....

Why django finds errors inside comment blocks in template?

Sometime Django finds an error in a template. I Would like to comment out the row to debug but django keeps to find the error even in the comment.
For example this link give me an error because url 'prova' don't exist.
<!--Prova<br/>-->
another example: here {{ field }} give an error (and I don't know why but this is another problem)
<!--{% for field in form.visible_fields %}
{{ field.errors }}
{{ field.label }}
{{ field }}
{{ field.help_text }}
<br />
{% endfor %}-->
Maybe there's another way to comment?
Thank you
Django still parses the code; it doesn't care about HTML comments. If you want to ensure that it does not get rendered at all, you should use the Django comment tags, {% comment %}...{% endcomment %}.
For a single line, you can wrap things in {# ... #}.
See the docs.

Add a * to required field's label

I want to add a '*' before (or after) label's text in case the filed is required.
I can do this now by using this in my template:
{% for field in form %}
<label for="{{ field.name }}">
{{ '*' if field.flags.required }}{{ field.label.text }} :
</label>
{{ field }}
{% endfor %}
Is there some better way than this, at least a way to avoid adding label element manually?
That's how you do it, there is no simpler way than by checking the flag and then outputting what you want. You can change the text of the label somewhat more directly, though. You could also make a macro out of it so you don't need to copy and paste as much for each field in each template. Create a template "forms.html":
{% macro form_field(field) %}
{% if field.flags.required %}{{ field.label(text='*' + field.label.text) }}
{% else %}{{ field.label }}{% endif %}:
{{ field }}
{% endmacro %}
Then use it in other templates:
{# import the macro at the top of the template #}
{% from "forms.html" import form_field %}
{# use it in your for loop #}
{% for field in form %}
{{ form_field(field) }}
{% endfor %}
I've tried to find a better answer to this question and in my case this css trick worked very well and I did not have to alter anything else:
add a file to the-flask-wtf-project/app/static/styles/custom.css
with the following content in it:
div.required label:after {
content: " *";
color: red;
}
Then make sure to include the css in base.html (or all your templates using forms) inside the {% block scripts %}
<link rel="stylesheet" type="text/css" href="{{url_for('static',filename='styles/custom.css') }}">
I still consider myself a newbie so if this tips is off somehow please chime in.
Just my 2 cents, that I was very pleased with and could not find easily on any other thread here or elsewhere.
Following Henrik Andreasson's answer (thanks to his suggestion), I would like to add some more precision, because I spent few hours understanding how to avoid to do macros, like on the answer of davidism.
In the html file, you should add the attribute required:
<label for="{{ field.name }}" required="">
In my case, I was also doing a project on Flask with WTForms, so instead of what was written above, I did:
{{ form.field.label(required=form.field.flags.required) }}
In the css file, you should add:
label[required]:after {
content: " *";
}
which means:
after all the tags label containing the attribute required, add all the things in the dictionary.
Hope it helps.

python, create dynamic html name values..

i need a small help.. i am looping over objects which are in db and rendering all objects to template, so far so good. but what i want is that every rendered html name field should have different name so that i can refer to all of them latter. my code is this:
{% for p in products %}
<input type="number" name="name1" value="{{p.arg1}}" size="12"/>
<input type="number" name="name2" value="{{p-arg2}}" size="12"/>
{% endfor %}
but if i have 4 objects in DB, then i will have 8 rendered input fields in template, but all of them will have the "name" value as name1 and name2, is it possible to create 8 different names dynamically so that i can refer to all of them in my view again...
thanks
Use the forloop.counter variable
{% for p in products %}
<input type="number" name="name-{{forloop.counter}}-arg1" value="{{p.arg1}}" size="12"/>
<input type="number" name="name-{{forloop.counter}}-arg2" value="{{p.arg2}}" size="12"/>
{% endfor %}
The forloop.counter is 1-indexed. There is also the forloop.counter0 for indices
starting with 0.
Are you sure though that django formsets isn't what you need?

Categories

Resources