I have the validator
EqualTo('pass_confirm', message='Passwords Must Match!')
which when the passwords don't match shows an error like this.
How do I stylize the error message to be red? I've already tried changing the message to a <span style="color:red">, but it renders plain text and not the HTML.
Flask provides an error element in your form for you. To be able to use it, include the following on your template:
Generic example:
{{ form.password.label }}<br>
{{ form.password(size=32) }}<br>
{% for error in form.password.errors %}
<span style="color: red;">[{{ error }}]</span>
{% endfor %}
Related
Beautify indentation is ignoring Jinja2.
I am using Beautify - HookyQR to help with formatting and indentation.
HTML, Python, CSS ... everything works fine. But when I start using Python, Flask with Jinja2 as I save it, it just ignores all the content and I lose all the indentation.
This is what I was expecting:
<div class="form-group">
{{ form.username.label(class="form-control-label") }}
{% if form.username.errors %}
{{ form.username(class="form-control form-control-lg is-invalid") }}
<div class="invalid-feedback">
{% for error in form.username.errors %}
<span>{{ error }}</span>
{% endfor %}
</div>
{% else %}
{{ form.username(class="form-control form-control-lg") }}
{% endif %}
</div>
This is the code when I save:
<div class="form-group">
{{ form.username.label(class="form-control-label") }}
{% if form.username.errors %}
{{ form.username(class="form-control form-control-lg is-invalid") }}
<div class="invalid-feedback">
{% for error in form.username.errors %}
<span>{{ error }}</span>
{% endfor %}
</div>
{% else %}
{{ form.username(class="form-control form-control-lg") }}
{% endif %}
</div>
I was searching about this, but I just cannot find any tips.
What I use:
I am a PC user and my text editor is VS Code, Win 10.
Extensions uses on VSCODE:
Beautify - Live Server - Material Icon Theme - Material Theme - SQL Server (mssql)
I ran into the same problem. I found this extension though which seems to do the job.
Here's a link to it
https://marketplace.visualstudio.com/items?itemName=monosans.djlint
or just search "djlint" in the extensions marketplace.
You also need to install the djlint python package with the command:
pip install djlint
You will need to add these lines to your settings.json file.
"[jinja][jinja-html][html]": {
"editor.defaultFormatter": "monosans.djlint",
},
The first line is telling VS Code that the following settings are just for the file types jinja, jinja-html and html. If you're using different file types insert yours here.
The next line is just telling VS Code to use DJLint's formatter for those file types.
Let me know if that helps!
The answer by #Tyler Petrov is pretty spot on.
If you want some more context feel free to check out my solution :-)
I have a form that makes 14 fields, an opening and closing field for each day. I am having problems displaying each on its own, so I can include the days in between. My form is making fields such as 'open_time_1', 'close_time_1' up to 7. I currently have
{{ schedule_form.fields.close_time_1 }}
in my template, which was promising, but is causing
How can I get the nitty gritty of django form fields in general to display manually like that? Thank you
I would try {{ schedule_form.close_time_1 }}.
This renders the field without any label markup. This is some code I use to render a field with bootstrap:
<div class="form-group">
<span class="field-label">{{ field.label_tag }}</span>
{% if field.field.required %}<span class="required">*</span>{% endif %}
<span class="field-item">{{ field }}</span>
<div class="field-help">{{ field.help_text }}</div>
{% if field.errors %}<div class="alert alert-warning" role="alert">{{ field.errors }}</div>{% endif %}
</div>
Where field is eg. schedule_form.close_time_1.
More on the topic in Django docs: Working with forms.
I am writing some basic tests and have a test failing.
def test_new_user_registration(self):
self.client.get('/user/register')
form = RegistrationForm(
email=u'crow#crow.com',
first_name=u'Alex',
last_name=u'Frazer',
username=u'crow',
password=u'fake_password',
confirm_password=u'fake_password'
)
self.assertTrue(form.validate())
The assertion error is failing on form.validate(), but how can I view what the validation errors are?
Use form.errors:
errors
A dict containing a list of errors for each field. Empty if the form
hasn’t been validated, or there were no errors.
You can print the errors by adding the following: print form.errors.items().
I had the same problem, and couldnt find the answer anywhere. This is a snippet from my index.html
<div class="all">
<div class="form-group">
{{ form.phone.label(id="label1") }}
{% if form.phone.errors %}
{{ form.phone(class="form-control form-control-lg is-invalid") }}
<div class="invalid-feedback">
{% for error in form.phone.errors %}
<span>{{ error }}</span>
{% endfor %}
</div>
{% else %}
{{ form.phone(class="form-control", placeholder="Enter Your Phone Number", )}}
{% endif %}
</div>
</div>
And in my forms.py
class AddContestant(FlaskForm):
number = StringField('Phone number', validators=[DataRequired(), Length(min=10, max=15, message="Your phone number should be more than 10 digits and less than 15")])
I understand that flash() takes only string and displays that in the redirected page.
I m trying to send html through flash
message = "<h1>Voila! Platform is ready to used</h1>"
flash(message)
return render_template('output.html')
output.html
<div class="flashes">
{% for message in get_flashed_messages()%}
{{ message }}
{% endfor %}
</div>
But it is displaying as string <h1>Voila! Platform is ready to used</h1> is there any way to overcome this.
Where possible, a secure approach is to wrap your string in a Markup object before passing it to the template:
Python code:
from flask import Markup
message = Markup("<h1>Voila! Platform is ready to used</h1>")
flash(message)
return render_template('output.html')
Jinja2 Template:
<div class="flashes">
{% for message in get_flashed_messages() %}
{{ message }}
{% endfor %}
</div>
Using {{message|safe}} will work, but also opens up the door for an attacker to inject malicious HTML or Javascript into your page, also known an an XSS attack. More info here if you're interested.
Use the safe filter:
<div class="flashes">
{% for message in get_flashed_messages()%}
{{ message|safe }}
{% endfor %}
</div>
For cases where you might want to control the CSS applied depending on the status of message (Success | Error), the following code might be useful:
{% for category, msg in get_flashed_messages(with_categories=true) %}
<div class="alert {{ category }} alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
{{ msg|safe }}
</div>
{% endfor %}
Another way is to call render_template to the external HTML file and passing that to Markup class.
main/routes.py
from flask import render_template, flash, Markup
from . import blueprint
#blueprint.route("/user")
def user():
flash(Markup(render_template("templates/user.html", name="John Doe"))
return render_template("templates/home.html")
templates/user.html
<h1>User: {{ name }}</h1>
I'm having a peculiar problem with a django template I'm setting up: I have a {{ name }} variable that I'm passing to my template, and at the same time, I have a notes list coming from a client-side api that has both a {{ name }} and a {{ body }}.
Whenever I try to print out the name of the note, the other {{ name }} shows up. Which is odd. Here's my code for the notes:
<div class="notes">
{% for note in notes %}
<p><strong>{{ name }}</strong></p>
<p>{{ body }}</p>
{% endfor %}
</div>
Am I doing something wrong? Is there a context operator I can use or something?
<div class="notes">
{% for note in notes %}
<p><strong>{{ note.name }}</strong></p>
<p>{{ note.body }}</p>
{% endfor %}
</div>
This is a common mistake that is made when working with Handlebars alongside Django since Handlebars changes scope automatically for you. All you need to do is refer to the note variable you created with the for loop:
<div class="notes">
{% for note in notes %}
<p><strong>{{ note.name }}</strong></p>
<p>{{ note.body }}</p>
{% endfor %}
</div>
More info here: https://docs.djangoproject.com/en/1.5/ref/templates/builtins/#std:templatetag-for