How can I set the class of a checkbox label with wtforms? - flask-wtforms

I would like to use Bootstrap 4 forms. This means I need to add the class form-check-label to the label of a checkbox. How can I do that?
Minimal Code Sample
requirements.txt
Flask==1.0.2
WTForms==2.2.1
Flask-WTF==0.14.2
app.py:
from flask import Flask, render_template
from flask_wtf import FlaskForm
from wtforms import BooleanField, StringField, PasswordField, SubmitField
app = Flask(__name__, template_folder="templates")
app.config['SECRET_KEY'] = 'http://flask.pocoo.org/docs/1.0/quickstart/#sessions'
class LoginForm(FlaskForm):
username = StringField('Username')
password = PasswordField('Password')
remember_me = BooleanField("Remember Me")
submit = SubmitField('Submit')
#app.route('/')
def index():
form = LoginForm()
return render_template('login.html', form=form)
app.run()
templates/login.html:
<form action="" method="post" class="form form-horizontal" role="form">
{{ form.hidden_tag() }}
<div class="form-group">
{{ form.username.label }}<br>
{{ form.username(size=32, class_="form-control") }}<br>
{% for error in form.username.errors %}
<span style="color: red;">[{{ error }}]</span>
{% endfor %}
</div>
<div class="form-group">
{{ form.password.label }}<br>
{{ form.password(size=32, class_="form-control") }}<br>
{% for error in form.password.errors %}
<span style="color: red;">[{{ error }}]</span>
{% endfor %}
</div>
<div class="form-check">
{{ form.remember_me.label }}<br> # form-check-label
{{ form.remember_me(value='n', class_="form-check-input") }}
{% for error in form.remember_me.errors %}
<span style="color: red;">[{{ error }}]</span>
{% endfor %}
</div>
{{ form.submit(class_="btn btn-primary") }}
</form>

The solution turned out to be super simple - I can call .label also as a function identical to the other elements:
{{ form.remember_me.label(class_="form-check-label") }}

Related

Error field wasn't correctly shown in django form

I'm using Django form and trying to loop through the fields in my template.
I did it like this:
<form method = "post">
<span>
{% for error in form.errors %}
<p>{{ error }}</p>
{% endfor %}
</span>
{% for field in form %}
<span>
{{ field.label_tag }}
</span>
<div>
{{ field }}
</div>
{% endfor %}
{% csrf_token %}
<button type = "submit">
</form>
However, when I did this, the error field shown in the template was displayed as "all".
Beside this everything's fine with this form.
I'm wondering what's going on.
Many thanks in advance!
Try using the form like this(remember to add the CSS):
<form method = "post">
{% csrf_token %}
{% for field in form %}
{{ field.label_tag }}
{{ field }}
{{field.errors.as_text|cut:'* '}}
{% endfor %}
<button type = "submit">
</form>

How to send information on my email from django form? - Django 2

How to send information on my email from django form. Now I can see information only in my console output on my cmd
template:
{% extends 'base.html' %}
{% load widget_tweaks %}
{% block title %}
Contact Us
{% endblock %}
{% block content %}
<h2 class="mt-4 ml-4">Contact Me</h2>
<form method="post">
<div class="container mt-4">
{% csrf_token %}
<div class="col-md-4">
{{ form.subject.label }}
{% render_field form.subject class+="form-control" %}
</div>
<div class="col-md-4">
{{ form.email.label }}
{% render_field form.email type="email" class+="form-control" %}
</div>
<div class="col-md-4">
{{ form.message.label }}
{% render_field form.message class+="form-control" rows="4" cols="6" %}
</div>
<div class="form-actions">
<button type="submit" class="btn btn-primary mt-2 ml-3">Send</button>
</div>
</div>
</form>
{% endblock %}
forms.py:
from django import forms
class ContactForm(forms.Form):
email = forms.EmailField(required=True)
subject = forms.CharField(required=True)
message = forms.CharField(widget=forms.Textarea, required=False)
views.py:
from django.core.mail import send_mail, BadHeaderError
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render, redirect
from .forms import ContactForm
def emailView(request):
if request.method == 'GET':
form = ContactForm()
else:
form = ContactForm(request.POST)
if form.is_valid():
subject = form.cleaned_data['subject']
email = form.cleaned_data['email']
message = form.cleaned_data['message']
try:
send_mail(subject, message, email, ['yarik.nashivan#gmail.com'])
except BadHeaderError:
return HttpResponse('Invalid header found.')
return redirect('success')
return render(request, "email.html", {'form': form})
def successView(request):
return HttpResponse('Success! Thank you for your message. <p>You will be redirected to the main page in 3 seconds.</p> <meta http-equiv="refresh" content="3;url=/"> ')
Don't look at it: fgkjdfldfjgndfkgndfskj vdafk kjdsjaf jjjfd jdsaf dj fdsjn dnjndfj jdffjk hdsffdfgfdb sfdf
Well, you are using console backend, that is why you are seeing the message in console. If you use SMTP backend, then you can send this email to your acccount. For that, you need to configure like this:
First you need to update the backend in settings.py:
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
Then update the smtp configurations in settings.py:
# this configuration is for gmail
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'test#gmail.com'
EMAIL_HOST_PASSWORD = 'test'
EMAIL_PORT = 587
For details, please check the email documentation for Django.

How i can insert contact form 7 short-code in twig file

I want to show contact form which i am using into
but shorcode not showing form on frontend
How can I show contact form 7 with .twig file?
<div class="our_form">
{{ wp.do_shortcode('[contact-form-7 id="766" title="Contact form 1"]') }}
</div>
<form action="{{ post.link }}" class="contact-form" method="post" {{ form_enctype(form) }}>
<div class="contact-form__row">
{% spaceless %}
{{ form_row(form.name, {}) }}
{{ form_row(form.email, {}) }}
{{ form_row(form.subject, {}) }}
{% endspaceless %}
</div>
{{ form_row(form.message, {}) }}
{{ form_widget(form) }}
<button class="btn btn--primary caps">Send</button>
</form>
how about running this like that:
{% filter shortcodes %}
[contact-form-7 id="766" title="Contact form 1"]
{% endfilter %}
Reference: https://timber.github.io/docs/guides/wp-integration/#shortcodes

Django crudbuilder & Bootstrap datepicker

Django==1.11.7
django-crudbuilder==0.2.5
Using Bootstrap datepicker. Now trying to use the datepicker in a crud form for a date field.
In a normal Django form, this would work:
self.fields['payment_date'].widget.attrs.update({'class': 'datepicker'})
But how can the class:datepicker be set for a particular field in a crud form?
The documentation doesn't seem to mention anything useful on css or html class.
Start with implementing custom templates.
Copy over the instance templates in crudbuilder/templates/crudbuilder/instance/ into your application template directory.
Replace the template location for the included form template in all the copied over instance templates .e.g. create.html
...
{% block main_content %}
<div class='container'>
<h3>Create {{actual_model_name|title}}</h3>
<hr/>
{% include "my_app/widgets/form.html" %}
</div>
{% endblock %}
In my_app/templates/my_app/widgets/form.html, write this instead to set the datepicker class on payment_date. (Original code was copied from django-cruid)
{% load crudbuilder %}
{% include "datepicker.html" %}
<form action="." method="post" enctype="multipart/form-data" class="form-horizontal" novalidate>
{% csrf_token %}
{% for field in form %}
<fieldset class={% if field.errors %} "form-group has-error" {% else %} "form-group" {% endif %} >
{{ field|label_with_class:"col-sm-2 control-label" }}
<div class="col-xs-4">
{% if field.name == 'payment_date' %}
{{ field|input_with_class:"form-control datepicker" }}
{% endif %}
{{ field|input_with_class:"form-control" }}
{{ field.errors }}
</div>
</fieldset>
{% endfor %}
<div class="form-group">
<div class="col-sm-offset-2 col-sm-12">
<input type="submit" value="Save" class="btn btn-success" />
</div>
</div>
</form>
Finally, set your crud form to use your custom templates.
class PersonCrud(BaseCrudBuilder):
...
custom_templates = {
'list': 'my_app/list.html',
'create': 'my_app/create.html',
'detail': 'my_app/detail.html',
'update': 'my_app/update.html',
'delete': 'my_app/delete.html'
}

Symfony splitted embedded form

I work with a symfony embedded form to manage my translated fields for a given entity. My principal entity has a boolean field and I have multiple text fields for each translation.
I do not use the translatable doctrine extension and I do not want to use it.
In my FormType, I use a CollectionType to embed the translated fields in my form, and in the template, I use the form theme to customize the HTML.
This is my problem : I would like to group fields in my form to optimize UX but once I call the form_widget on my field, I cannot use it a second time. I would like to show 2 fields for a given language and then another field for another language further in the form. How can I solve my problem ?
This is a twig example that illustrate my problem.
{% form_theme form _self %}
{% block _service_translations_entry_widget %}
<div>
{% if name == 0 %}
<div class="s12 m6 l6">
{{ form_label(form.title) }}
{{ form_errors(form.title) }}
{{ form_widget(form.title) }}
</div>
<div class="s12 m6 l6">
{{ form_label(form.subtitle) }}
{{ form_errors(form.subtitle) }}
{{ form_widget(form.subtitle) }}
</div>
{% endif %}
{% if name == 1 %}
<div class="s12 m12 l12">
{{ form_label(form.desc) }}
{{ form_errors(form.desc) }}
{{ form_widget(form.desc) }}
</div>
{% endif %}
</div>
{% endblock %}
{% block body %}
{{ form_start() }}
{{ form_errors(form) }}
<div>
<div class="s12 m12 l12">
{{ form_label(form.doubleBlock) }}
{{ form_errors(form.doubleBlock) }}
{{ form_widget(form.doubleBlock) }}
</div>
</div>
<div id="block-1">
{{ form_widget(form.translations) }}
</div>
<div>
<div class="s12 m6 l6">
{{ form_label(form.activedStyle) }}
{{ form_errors(form.activedStyle) }}
{{ form_widget(form.activedStyle) }}
</div>
<div class="s12 m6 l6">
{{ form_label(form.checkoutOption) }}
{{ form_errors(form.checkoutOption) }}
{{ form_widget(form.checkoutOption) }}
</div>
</div>
<div id="block-2">
{{ form_widget(form.translations) }}
</div>
{{ form_widget(form.save) }}
{{ form_rest(form) }}
{{ form_end(form) }}
{% endblock body %}
As you say, you can’t reuse a field.
My suggested approach would be to add an additional field to the form, translations_extra, which either isn’t mapped to or persisted by the entity. Extract the data in the controller on form submission and then add it to the translations collection before persisting.

Resources