Skip to content

Instantly share code, notes, and snippets.

@mekza
Last active December 23, 2022 23:04
Show Gist options
  • Save mekza/516f172278c328468ea0 to your computer and use it in GitHub Desktop.
Save mekza/516f172278c328468ea0 to your computer and use it in GitHub Desktop.
WTForms Select Field for country
from wtforms import SelectField
import pycountry
class CountrySelectField(SelectField):
def __init__(self, *args, **kwargs):
super(CountrySelectField, self).__init__(*args, **kwargs)
self.choices = [(country.alpha_2, country.name) for country in pycountry.countries]
@HarryZ10
Copy link

How do i implement gists?

@mekza
Copy link
Author

mekza commented Apr 13, 2020

@HarryZ10 I updated the gist, you can copy/paste this snippet and use CountrySelectField directly into your form.

@dhernandezgt
Copy link

how to pass the form to HTLM page using Flask

@app.route
form = CountrySelectField()
return render_template('up_profile.html', form=form)

the webpage.html

<div class="form-group">
  <fieldset>
    {{ form.self.choice.label(class="form-control-label") }}
    {{ form.self.choice(class="form-control form-control-lg") }}
  </fieldset>
</div>

if I use self.choice or only choice the error es same in the:
jinja2.exceptions.UndefinedError: 'wtforms.fields.core.UnboundField object' has no attribute 'self' or inja2.exceptions.UndefinedError: 'wtforms.fields.core.UnboundField object' has no attribute 'choice'

thanks

@mekza
Copy link
Author

mekza commented May 14, 2020

@dhernandezgt My snippet is a Field not a Form, you can find more info on Fields and Forms here https://wtforms.readthedocs.io/en/2.3.x/crash_course/

@samos123
Copy link

I created a package for this using your gist and also a StateSelectField that uses a similar approach.

Repo: https://github.com/samos123/wtform-address

package: https://pypi.org/project/wtform-address/0.1.1/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment