How to iterate through numbers in django - python

I am new to Django. I just want to build an online resume based on the details given by the user.
I have separate HTML files for taking the user input and for displaying the resume.
I took the user input for the certification field like this:
<div class="box"><input type="text" name="certificate1" placeholder="Certificate-name"> <input type="text" name="institute1" placeholder="Institute-name"></div><br>
<div class="box"><input type="text" name="certificate2" placeholder="Certicate-name"> <input type="text" name="institute2" placeholder="Institute-name"></div><br>
<div class="box"><input type="text" name="certificate3" placeholder="Certicate-name"> <input type="text" name="institute3" placeholder="Institute-name"></div><br>
<div class="box"><input type="text" name="certificate4" placeholder="Certicate-name"> <input type="text" name="institute4" placeholder="Institute-name"></div><br>
<div class="box"><input type="text" name="certificate5" placeholder="Certificate-name"> <input type="text" name="institute5" placeholder="Institute-name"></div><br>
<div class="box"><input type="text" name="certificate6" placeholder="Certicate-name"> <input type="text" name="institute6" placeholder="Institute-name"></div><br>
And the code which I have written in views.py file is this:
if(request.method=="POST"):
dictionary = {str(i):request.POST[i].capitalize() for i in request.POST}
return render(request,"form/resume.html",dictionary)
And the code which I have written for displaying certifications in the resume is this:
{% if certificate1 %}
<li>{{certificate1}}, {{institute1}}</li>
{% endif %}
{% if certificate2 %}
<li>{{certificate2}}, {{institute2}}</li>
{% endif %}
{% if certificate3 %}
<li>{{certificate3}}, {{institute3}}</li>
{% endif %}
{% if certificate4 %}
<li>{{certificate4}}, {{institute4}}</li>
{% endif %}
{% if certificate5 %}
<li>{{certificate5}}, {{institute5}}</li>
{% endif %}
{% if certificate6 %}
<li>{{certificate6}}, {{institute6}}</li>
{% endif %}
But I feel the code that I have written in displaying certifications in resume [2nd code] is not efficient. Is there any other way of writing the 2nd code? I want to know, how can we use for loop if possible. Or is there any other way? Thanks in advance for your valuable answers.

You can group all your data in one array and pass them in your render function so you could iterate it in your Jinja template

Send certificates as a list to template like this:
certificates = [
{ "certificate": certificate1, "institute": institute1},
{ "certificate": certificate2, "institute": institute2}
]
Then in template, display it like this:
{% for c in certificates %}
<li>{{c.certificate}}, {{c.institute}}</li>
{% endfor %}

Try to use arrays so you can easily iterate through it.
or if you just want to write in that way
use string concatenation for the variable name like:
{% for x in '123456' %}
{% with y=forloop.counter|stringformat:"s" %}
{% with names="certificate"|add:y %}
{% if names %}
<li> {{name}} </li>
{% endif %}
{% endwith %}
{% endwith %}
{% endfor %}
See this for more info:
How can I concatenate forloop.counter to a string in my django template

Related

flask render_template passed variable not being used in the template

I'm currently working on a project and I'm having a problem with flask and render_template. When I pass a variable into render_template, it doesn't actually pass through to the template. I've already tried putting the string into a variable and a few other things but nothing has worked so far.
Here's the function I'm returning:
return render_template("sell.html", error="Invalid Ticker")
Here's "sell.html":
{% extends "layout.html" %}
{% block title %}Sell{% endblock %}
{% block main %}
<h1>Sell a Stock!</h1>
{% if error is defined %}
<div class="alert alert-danger">
{{error}}
</div>
{% endif %}
{% if success is defined %}
<div class="alert alert-success">
{{success}}
</div>
{% endif %}
<form action="/sell" method="post">
<div class="form-group">
<label for="ticker">Ticker:</label>
<input type="text" class="form-control" id="ticker" name="ticker">
</div>
<div class="form-group">
<label for="buynum">Shares:</label>
<input type="number" class="form-control" id="sellnum" name="sellnum">
</div>
<button type="submit" class="btn btn-primary">Sell</button>
</form>
{% endblock %}
The problem is not in the render_template function it is working fine. The problem is error is defined doesn't exists in jinja2.
just try a simpler html example to test:
{% block title %}Sell{% endblock %}
{% block main %}
<p> {{error}} </p>
{% endblock %}
so change :
{% if error is defined %}
and
{% if success is defined %}
to
{% if error %}
{% if sucess %}

Django: Extent with snippets or better solution

I have the following template:
{% extends "account/base.html" %}
{% load i18n %}
{% load account %}
{% load crispy_forms_tags %}
{% block head_title %}{% trans "Password Reset" %}{% endblock %}
{% block content %}
<div class="container">
<div class="row justify-content-center">
<div class="col-8">
<h1>Reset your password</h1>
{% if user.is_authenticated %}
{% include "account/snippets/already_logged_in.html" %}
{% endif %}
<p>{% trans "Forgotten your password? Enter your e-mail address below, and we'll send you an e-mail allowing you to reset it." %}</p>
<form method="POST" action="{% url 'account_reset_password' %}" class="password_reset">
{% csrf_token %}
{{ form|crispy }}
<button type="submit" class="btn btn-primary">Reset My Password</button>
</form>
<p><em>{% blocktrans %}Please contact us if you have any trouble resetting your password.{% endblocktrans %}</em></p>
</div>
</div>
</div>
{% endblock %}
account/base.html contains this here:
{% extends "base.html" %}
base.html then contains tags etc. I am currently struggling with finding the best solution while considering DRY. In my template I have written:
<div class="container">
<div class="row justify-content-center">
<div class="col-8">
[more text]
</div>
</div>
</div>
I have several of these templates and in each of them I am currently writing the same ... I am now wondering is the right solution to include these opening / closing div-tags in two files and then add
{% include "div-open.html" %}
[more text]
{% include "div-closing.html" %}
Or is there any better solution to this? It doesn't feel right, that's why I am asking you now how you would solve this.
I depends if HTML repetition should be considered as DRY violation. I you have custom form fields which you want to include, than having {% include 'simple_custom_field.html' with field=form.some_fied %} where
simple_custom_field.html
<input
type="{{ field.field.widget.input_type }}"
class="form-control {{ field.field.widget.attrs.class }} {{ class }}"
id="{{ field.id_for_label }}"
name="{{ field.html_name }}"
placeholder="{{ field.label }}"
{% if field.value is not None %} value="{{ field.value }}"{% endif %}>
or like that...
is good idea, or you can render whole form like that also if you have long blocks or separate blocks of HTML in multiple files, then go for it. But its bad idea for including simple and fundamental parts of HTML. It should be transparent for the programmer.
If you want to do it another way, there are ways how to add custom template tags and "modify" the language you write templates in.
Here is docs how to do it: Writing custom template tags | Django docs

flask-admin: revise the button text

I haven't found similar questions on stackoverflow, I'd like to change the save button to submit or confirm on the edit form. I know this might not be easily changed. Thanks for any advise in advance.
After search in the code of flask-admin, I found the button is rendered with macro render_form, render_form_buttons, extra. The value of these buttons is hard code with {{ _gettext("blabla") }}.
As these buttons are not fields of data model, we can't use rendering rules to custom the value. I think there are two work arounds to get this done:
change the macro which render these buttons in the source of flask-admin(render_form_buttons, extra)
flask-admin use flask-babelex to do localization({{ _gettext("blabla") }}), you can 'translate' Save to submit or confirm with flask-babelex
UPDATE:
You can custom edit.html in your own template directory.
{% extends 'admin/model/edit.html' %}
{% from 'admin/lib.html' import extra with context %}
{% from 'admin/lib.html' import form_tag with context %}
{% from 'admin/lib.html' import render_form_fields with context %}
{% macro my_render_form_buttons(cancel_url, extra=None, is_modal=False) %}
<hr>
<div class="form-group">
<div class="col-md-offset-2 col-md-10 submit-row">
<input type="submit" class="btn btn-primary" value="{{ _gettext('Submit') }}" />
{% if extra %}
{{ extra }}
{% endif %}
{% if cancel_url %}
<a href="{{ cancel_url }}" class="btn btn-danger" role="button" {% if is_modal %}data-dismiss="modal"{% endif %}>{{ _gettext('Cancel') }}</a>
{% endif %}
</div>
</div>
{% endmacro %}
{% macro my_render_from(form, cancel_url, extra=None, form_opts=None, action=None, is_modal=False) -%}
{% call form_tag(action=action) %}
{{ render_form_fields(form, form_opts=form_opts) }}
{{ my_render_form_buttons(cancel_url, extra, is_modal) }}
{% endcall %}
{% endmacro %}
{% block edit_form %}
{{ my_render_form(form, return_url, extra(), form_opts) }}
{% endblock %}

Using stylesheets with django-widget-tweaks?

I'm struggling to understand how to use Django-Widget-Tweaks with a stylesheet. For example, here's my basic form with bunch of CSS classes pulled from my stylesheet - obviously not yet wired up with Django.
<form name="form">
<div class="md-form-group float-label">
<input type="email" class="md-input">
<label>Email</label>
</div>
</form>
How should this be used with Django-Widget-Tweaks? I'm presuming it's something like this but I'm struggling to understand where the div classes go...
<div>
{% load widget_tweaks %}
{{ form.myform|add_class:"md-form-group float-label md-input" }}
</div>
Thanks!
This is how I do it by using render_field tag. Hope this helps.
{% load widget_tweaks %}
<form name="form">
{% for field in form %}
<div class="md-form-group float-label">
{% render_field field class="md-input" %}
<label>{{ field.label_tag }}</label>
</div>
{% endfor %}
</form>

Getting from POST in included .html page in Django

I am trying to get the POST values of an .html page that has included pages via {% include %} in Django. However, it returns only the POST from the initial html page.
My inner html that is included has the snippet of code:
div id="edit_parameters">Edit Parameters</div>
<div data-id="{{job.slug}}" id="{{job.slug}}" class="collapse">
<form class = "form-inline" method="post">
{% csrf_token %}
{% for parameter in job.get_object.parameters %}
<p>
<input type="text" class="input-small" name="{{parameter}}" value="" id ="{{parameter}}-input" placeholder="{{parameter}}">
</p>
{% endfor %}
<button type="submit" class="btn btn-primary run-job">Submit</button>
</form>
</div>
{% else %}
<div>
No editable parameters for this job.
</div>
{% endif %}
And my outer HTML file has a snippet:
<ul id="available-jobs">
{% if jobs_same_io_type and jobs_diff_io_type %}<h3> Current Step </h3>
{% elif jobs_same_io_type %} <h3> Next Step </h3> {% endif %}
{% for job in jobs_same_io_type %}
{% include "includes/job_li.html" with add=1 %}
{% endfor %}
{% if jobs_diff_io_type %} <h3> Next Step </h3> {% endif %}
{% for job in jobs_diff_io_type %}
{% include "includes/job_li.html" with add=1 %}
{% endfor %}
{% if not jobs_same_io_type and not jobs_diff_io_type %}
<li class="full-height">There are no more available jobs.</li>
{% endif %}
</ul>
<fieldset class="submit">
{% csrf_token %}
<input type="hidden" name="job_to_run" value="" id="job-to-run" />
<input type="hidden" name="workflow_jobs" value="" id="ordered-jobs" />
<input type="hidden" name="job_to_edit" value="" id="job-to-edit" />
<input type="hidden" name="job_to_add" value="" id="job-to-add" />
<input type="hidden" name="job_to_remove" value="" id="job-to-remove" />
<input type="submit" name="done" value="I'm done, start the jobs" id="jobs-ready" />
</fieldset>
The everything that shows in post is in the inputs of the second snippet. But the parameters I want for the first snippet are not included when I use request.POST for all of the POST values.
Any help would be greatly appreciated in explaining why I am not getting the values from the included page and finding a possible solution. Thanks!
In HTML, only the fields in the form element that contain the submit button are included in the POST. the fields in your second file don't seem to be in any form at all, so they will never be posted.

Categories