Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use hidden input in an html form with Python+Jinja2

When I put this line in my html template, I can successfully pass the input string via a jinja2 variable into my Python code...

<label for="firstName">First name*</label>
<input type="text" name="fname" id="firstName" value="{{ fname }}">

However, when I attempt to pass a hidden input with the following line...

<input type="hidden" name ="contact_form" value="{{ active_form }}">

... I'm not seeing the value pass back to my Python code. I've not learned Javascript yet. Is there some Javascript required to pass hidden input values? What am I missing?

like image 740
bholben Avatar asked Oct 20 '22 10:10

bholben


1 Answers

I recommend using WTForms.

Example

from wtforms import TextField, validators, PasswordField, TextAreaField, HiddenField    
class ArticleCreateForm(Form):
        title = TextField('Title', [validators.Required("Please enter title.")],
                          filters=[strip_filter] )
        body = TextAreaField('Body', [validators.Required("Please enter body.")],
                             filters=[strip_filter])
        category = QuerySelectField('Category', query_factory=category_choice )
        person_name = HiddenField()

views.py

@app.route('/create', methods=['GET', 'POST'])
def article_create():
    if 'email' not in session:
        return redirect(url_for('signin'))
    person = Person.query.filter_by(email=session['email']).first()
    name = person.firstname
    article = Article()
    form = ArticleCreateForm()
    form.person_name.data = person.firstname
    if form.validate_on_submit():
        form.populate_obj(article)
        db.session.add(article)
        db.session.commit()
        return redirect(url_for('index'))
    return render_template('create.html', form=form, person=person, name=name)
like image 176
ajknzhol Avatar answered Oct 23 '22 00:10

ajknzhol