flask render_template passed variable not being used in the template - python

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 %}

Related

Javascript ID not showing reference to input text box - Django

{% extends 'halls/base.html' %}
{% block content %}
<div class="container">
<h2>Add Video to {{hall.title}}</h2>
<form method="post">
{% csrf_token %}
{% load widget_tweaks %}
{% for field in form %}
<div class="form-group {% if field.errors %} alert alert-danger {% endif %}">
{{ field.errors }}
{{ field.label_tag }}
{% render_field field class='form-control' %}
</div>
{% endfor %}
<button type="submit" class="btn btn-primary"> Add</button>
</form>
<br>
<h2>OR</h2>
<form>
{% for field in search_form %}
<div class="form-group ">
{{ field.errors }}
{{ field.label_tag }}
{% render_field field class='form-control' %}
</div>
{% endfor %}
</form>
<div id="search_results"></div>
<script type="text/javascript">
var delayTimer;
$("#id_search_term").keyup(function (){
clearTimeout(delayTimer);
$('#search_results').text('Loadingggg');
});
</script>
</div>
{% endblock %}
this is the HTML code. SO basically the whole idea here is when I inspect the search_form, it should give the id of the input box as "id_search_term". But when I inspect the box, it gives as id="id_search".
I am not able to find a way to reference the input box with the ID in the script tag

Request in Flask from a Form in HTML is returning None Value, What should I Do?

I am getting no value on request in flask. It is returning None value.
I have tried changing the method but no use.
The flask code:
#app.route("/login/user/book")
def searchbook():
bookname=request.form.get("search")
return render_template("message.html",heading=bookname ,message=" ")
The webpage:
{% extends "layout.html" %}
{% block heading %}Welcome to BookSarkar{% endblock %}
{% block body %}
<p>Welcome {{ name }}</p>
<form action="{{ url_for('searchbook') }}" method="get" class="form-group">
<div class="form-group">
<input type="text" name="search" class="form-control col-md-6 mt-5 mx-auto" placeholder="Search books">
<p style="text-align:center;">
<button type ="submit" class="btn btn-primary mt-2 mx-auto">Search</button>
</p>
</div>
</form>
<div class="fixed-top m-2">
<a class="btn btn-outline-primary" href="{{ url_for('logout') }}" role="button" style="float:right;">Log out</a>
</div>
{% endblock %}
The message webpage:
{% extends "layout.html" %}
{% block heading %}{{ heading }}{% endblock %}
{% block body %}
{{ message }}
<a class="btn btn-primary" href="{{ url_for('index') }}" role="button">Return to Home Page</a>
{% endblock %}
The layout page has no bugs as all other pages are working fine. I expected the webpage to show the given input but it is showing None
request.form contains values submitted via post or put, while your form uses get. Try using request.args.get("search") instead of request.form.get("search")

Flask square brackets and single quotas at showing all validation message at once

I have created a very simple login form with flask
email = StringField('E-Mail:', validators=[validators.DataRequired(message='E-mail needed.'), validators.email(u'Provide e-mail.')])
password = StringField('Password:', [validators.required(u'Password can't be empty.')])
And the macro which will create the form inside the template:
{% macro render_field(field) %}
<fieldset>
<div class="form-group">
{{ field(**kwargs) | safe }}
</div>
</fieldset>
{% endmacro %}
As you can see it is very simple form. In the flask tutorial it was showing validation erors for individual fields. But I just want to show them all at once on the top of the form.
Here is my template for that:
<div class="panel-body">
{% if loginForm.errors %}
<div class="alert alert-danger">
<ul>
{% for error in loginForm.errors %}
<li>{{ loginForm.errors[error] }}</li>
{% endfor %}
</ul>
</div>
{% endif %}
<form role="form" method="post" action="{{ url_for('login') }}">
{% from "_formhelper.html" import render_field %}
<fieldset>
{{ render_field(loginForm.email, class="form-control", placeholder="E-Mail") }}
{{ render_field(loginForm.password, class="form-control", placeholder="Password") }}
<button class="btn btn-lg btn-success btn-block">Login</button>
</fieldset>
</form>
</div>
As you can see, i placed my error section on the top of the form. But when
I post empty form, it shows the error messages like this:
['Password can't be empty'] instead of Password can't be empty
Why does it append square brackets and single quotas, start and end of the message? I don't know.
I know that this is an old question but if anyone else has this problem you can fix it by adding a for loop for the messages, something like this:
{% with messages = get_flashed_messages() %}
{% if messages %}
{% for message in messages %}
<div class="alert alert-warning my-5">
{{ message }}
</div>
{% endfor %}
{% endif %}
{% endwith %}

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 %}

Django Allauth Custom Login Does Not Show Errors

I am using Django Allauth for user flow in my project. I have successfully created my own set of templates which inherit from the standard Allauth templates and they work 95%. For some reason, however, I do not receive an error for an invalid login.
If I enter 'test#email' for the user I get a 'Please enter a valid email address' error but if I enter a proper email with an incorrect password it simply reloads the page but with no errors as to what went wrong. I've included my template below which has the {{ form.login.errors }} and {{ form.password.errors }} tags.
All guidance is appreciated, thank you.
Template:
<div id="search_container">
<div id="search_box_content">
{% block page_content %}
<h4>Login</h4>
<form class="" id="user-form" method="POST" action="{% url 'account_login' %}">
{% csrf_token %}
<h1> {{ form.login.errors }}</h1>
<h1> {{ form.password.errors }}</h1>
<div class="input_class">
<label for="login">Username: </label>
{{ form.login }}
</div>
<div class="input_class">
<label for="password">Password: </label>
{{ form.password }}
</div>
<div class="input_class" id="forgot_pass">
<label for="remember">
Remember Me? </label>
{{ form.remember }}
</div>
{% if redirect_field_value %}
<input type="hidden" name="{{ redirect_field_name }}" value="{{ redirect_field_value }}" />
{% endif %}
<div id="modal_bottom_bar">
<a class="button secondaryAction" id="forgot_pass" href="{% url 'account_reset_password' %}">Forgot your Password?</a>
<button class="primaryAction" id="login_submit" type="submit">Login</button></div>
</form>
{% endblock %}
</div>
</div>
Some errors are non field errors such as those errors which are raised for some custom validation and are not included in field.errors rather they are in form.non_field_errors:
So better use this snippet to show all errors which belongs to fields and to custom validation if you are rendering your form manually:
{% if form.errors %}
{% for field in form %}
{% for error in field.errors %}
<div class="alert alert-error">
<strong>{{ error|escape }}</strong>
</div>
{% endfor %}
{% endfor %}
{% for error in form.non_field_errors %}
<div class="alert alert-error">
<strong>{{ error|escape }}</strong>
</div>
{% endfor %}
{% endif %}

Categories