flask-wtforms field required - python

how i can add tag required on this flask code :
{{ form.youtube_href(type='url', class='form-control') }}
actual output is :
<input class="form-control" id="youtube_href" name="youtube_href" value="" type="url">
need this output bat give error :
<input class="form-control" id="youtube_href" name="youtube_href" value="" type="url" required>
im tried this bat give error :
{{ form.youtube_href(type='url', class='form-control', 'required') }}

As of WTForms 2.2 (June 2nd, 2018), fields now render the required attribute if they have a validator that sets the required flag, such as DataRequired and InputRequired. If for some reason you don't want to render the attribute, you can pass required=False. Or if you want to disable all browser validation, you can set the novalidate attribute in the form tag. In general you should prefer to leave browser validation enabled, because it prevents a request/response for simple validation, which is desirable.
You are passing a positional argument after keyword arguments, which is a syntax error. Instead, pass required=True, which will set a bare attribute on the tag. Check the flags on a field to see if a Required validator was set: field.flags.required is a boolean. Create a URLField rather than passing the type manually.
from flask_wtf import Form
from wtforms.fields.html5 import URLField
from wtforms.validators import InputRequired
class MyForm(Form):
youtube_href = URLField(validators=[InputRequired()])
form = MyForm()
print(form.youtube_href(required=form.youtube_href.flags.required))
# <input id="youtube_href" name="youtube_href" required type="url" value="">

To those who simply want to add the required attribute to their html input, this can be accomplished by following the comment mentioned by Raja Simon above. Simply call your field name in your template with required='required' Example:
<form>
...
{{myform.my_name_field(required='required')}}
{{myform.my_email_field(required='required')}}
...
</form>
The Above code will result in fields like so:
<input id="my_name_field" name="my_name_field" required="required" type="text" value="">

Related

Adding placeholder to form in Django when using django-filter

I am developing a web application which displays an html table using django-tables2 and which allows filtering this table using django-filter.
In my html template I can simply put {% filter.form %} and I am getting a full form for filtering my table which I think is really great and easy.
However, I would like to add placeholders to this form which would be in plane html (using Bootstrap4) something like this:
<div class="container">
<form>
<div class="form-group">
<label for="email">Email:</label>
<input type="email" class="form-control" id="email"
placeholder="ENTER PLACEHOLDER HERE" name="email">
</div>
</form>
</div>
(example taken form here:https://www.w3schools.com/bootstrap4/tryit.asp?filename=trybs_form_basic&stacked=h and edited)
How can I add a placeholder when working with django-filters and all I am doing is adding % filter.form %} to my template?
Edit:
My question was half complete. The answer given by #schwobaseggl works great for most filters. However, when having a RangeFilter and two fields show up (one for the max value and one for the min value) how to set two separate placeholders? One can put the same placeholder into both fields as explained here: How to put placeholder in Django date range filter.
When you define your Filter, provide the placeholder attribute via the attrs kwarg of the widget constructor:
# ...
from django.forms.widgets import TextInput, ...
class FooFilter(filters.FilterSet):
bar = filters.CharFilter(..., widget=TextInput(attrs={'placeholder': 'baz'}))
from django.forms.widgets import TextInput
class BikesFilter(django_filters.FilterSet):
sell_price = django_filters.NumberFilter()
sell_price__gt = django_filters.NumberFilter(field_name='sell_price', lookup_expr
='gte', label='sell price min', widget=TextInput(attrs={'placeholder': 'min'}))
sell_price__lt = django_filters.NumberFilter(field_name='sell_price', lookup_expr
= 'lte', label='sell price max', widget=TextInput(attrs={'placeholder': 'max'}))
class Meta:
model = Bike
fields = (
'sell_price'
)

How to manually make field in HTML? Django

in forms.py
class PlaceOrder(forms.ModelForm):
class Meta:
model = Order
fields = ["Product_ID","HowMany","DateSubmit",]
to call a form i usually use
{{ Form }}
that will render the form automatically
but is it possible to make it manually?
for example i want the form to be exactly like this
<input id="Product_ID" type="hidden" value="{{ Product.PId }}" >
<input id="HowMany" type="text">
<input id="DateSubmit" type="hidden" value="{{ date }}" >
i have tried wrapping them in
{% for field in form %}
but it gave the wrong output
Sorry if this is confusing
but i don't really know how to explain it,
i am still new to Django
You should be able to access individual fields in the form using something like
{{Form.Product_ID}}
which will give you the Product_ID field widget.
Now if you want to access the already pre-filled data you should be able to do so with
{{Form.Product_ID.label}}
or
{{Form.Product_ID.value}}
Also check:
https://docs.djangoproject.com/en/dev/topics/forms/#looping-over-the-form-s-fields

Flask-Bootstrap, flask-wtf, adding class to submit button

I'm using a flask-wtf submit button as follows:
{{ wtf.form_field(form.submit, button_map={'submit': 'primary'}) }}
I want to add a class to the submit button but I can not find anything about that,
I'm pretty new with this but this http://pythonhosted.org/Flask-Bootstrap/basic-usage.html#templates did not helped me a lot.
Anything to recommend?
It's super-easy, usually, so unless Flask-Bootstrap does something odd you can just tell it what you want the class to be:
{{ wtf.form_field(form.submit, class="something", button_map={'submit': 'primary'}) }}
Generally, anything you pass to the rendering function that isn't recognised will be added as a parameter to the html, so you can do things like:
{{ wtf.form_field(form.submit, cats="mew") }}
And your resulting html field would be something like <input cats="mew" id="name" name="name" type="text" value="">

Django BooleanField always checked even when value is false

I have a BooleanField in a standard Django Form defined as:
my_boolean_field = BooleanField(initial=True)
when I render my form with initial data, and my_boolean_field is set to an initial value of False, when the form renders it is still checked despite the fact that the value is false as the html shows:
<p><label for="id_2">my_boolean_field</label>:
<input checked="checked"
type="checkbox"
name="2"
value="False"
id="id_2" />
</p>
Has anyone else experienced this, or knows how to fix it so that when the initial data/input value is false then the checkbox is not checked?
UPDATE: Even if I remove the initial=True argument from the BooleanField the same thing happens.
Firstly, you can't have required=False on a BooleanField, use NullBooleanField instead:
https://docs.djangoproject.com/en/dev/ref/models/fields/#booleanfield
https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.NullBooleanField
let me know what the HTML output of the new widget is once you've done this?
EDIT
I assumed that this is a ModelForm. Is this a regular django.forms.Form?
EDIT 2
My test form:
from django import forms
class MyForm(forms.Form) :
"""The test form"""
my_boolean_field = forms.BooleanField(initial=True)
My template:
<div>
{{ form.my_boolean_field.label_tag }}
{{ form.my_boolean_field }}
{{ form.my_boolean_field.errors }}
</div>
This is what I get for output when I view page source. EDITED
<div>
<label for="id_my_boolean_field">My boolean field</label>
<input type="checkbox" name="my_boolean_field" id="id_my_boolean_field" />
</div>
My View NEW
form = MyForm(initial={'my_boolean_field':False})
What you are showing and what I'm seeing aren't matching up. paste your full form, view and template please?
EDIT 3
I only see output like this:
<div>
<label for="id_my_boolean_field">My boolean field</label>
<input checked="checked" type="checkbox" name="my_boolean_field" value="False" id="id_my_boolean_field" />
</div>
when I put False in quotes:
form = FormLogin(initial={'my_boolean_field':"False"})
I'm posting this answer because I had the same problem and Francis's answer didn't help me.
I eventually found the solution was to re-run manage.py syncdb. My fields had previously been IntegerField and I had converted them to BooleanField. BooleanField read the presence of value="0" in the database as being initialized and checked. This is regardless of what your model says. You want to see:
<input checked="checked" id="id_cost_track_destruction" name="cost_track_destruction" type="checkbox">
when you inspect an element. Since this bug shows up in the Django Admin panel, it has nothing to do with your forms.py.
This is purely a model and database issue. Try regenerating your database if you've changed your models.py field types.
For those who are using ModelForms, this is what worked for me:
password_required = forms.CheckboxInput(attrs={'checked' : ''})
This correctly generates the checkbox with it unchecked.

Python file upload "KeyError"

Whats wrong in this code?
Here is my HTML:
<html><body>
<form action="iindex.py" method="POST" enctype="multipart/form-data">
<p>File: <input type="file" name="ssfilename"></p>
<p><input type="submit" value="Upload" name="submit"></p>
</form>
</body></html>
This is my Python script:
#! /usr/bin/env python
import os, sys;
from mod_python import apache
import cgi
import cgitb; cgitb.enable()
form = cgi.FieldStorage(keep_blank_values=1)
fileitem = form["ssfilename"]
.....
This is the line where I get KeyError.
File "/Applications/MAMP/python/framework/Python.framework/Versions/2.6/lib/python2.6/cgi.py", line 541, in __getitem__
raise KeyError, key
KeyError: 'ssfilename'
Edit: Totally missed the part where you are doing keep_blank_values = 1; sorry, no idea what is wrong.
From http://docs.python.org/library/cgi.html:
Form fields containing empty strings are ignored and do not appear in the dictionary; to keep such values, provide a true value for the optional keep_blank_values keyword parameter when creating the FieldStorage instance.
Therefore, this is happening because this field was left blank.
I had the exact same problem, make sure you have the "enctype" set to "multipart/form-data" and use a default value in your field. So your form should look like this:
<form enctype="multipart/form-data" id="addFile" action="AddFile.py">
<input type="file" name="file" id="file" value=""/><br/>
<input type="submit" name="submit" value="Add File"/><br/>
</form>
I was also using a JQuery handler for my Form and was trying to serialize it and then posting it to my python handler, I bypassed that and it was going all fine, so you should try that also.
Check if you have no GET parameters in your form action URL.
If you need to pass on any data put it as form elements inside the form to be POSTed along with your upload file.
Then you find all your POSTed vars in cgi.FieldStorage.

Categories

Resources