Вопрос

I have a very simple form and table I am trhying to submit to utilizing python flask.

The sqllite table gets created by this class (this works):

class Country(db.Model):
    __tablename__ = 'countries'
    countryid = db.Column(db.Integer, primary_key=True)
    country = db.Column(db.String(65), unique=True, index=True)
    active = db.Column(db.Boolean, default=True)

    def __init__(self, country):
        """
        Used to create a Country object in the python server scope
        """
        self.country = country

The form is generated through this class:

class CountryForm(Form):
    country = StringField('Country name', validators=[Length(0, 64)])
    submit = SubmitField('Submit') 

The page displays through the view:

@main.route('/country', methods=['GET','POST'])
def show_CountryForm():
    form = CountryForm()
    print 'Form Values',form
    if form.validate_on_submit():
        ctry = Country(country=form.country.data)
        db.session.add(ctry)
        flash('The country has been added.')
        return redirect(url_for('chinese'))
    return render_template("country.html", form=form)

The html template page is:

{% extends "base.html" %}
{% import "_macros.html" as macros %}

{% block title %}Countries{% endblock %}

{% block page_content %}
<div class="container">
<form method="POST" action="/country">
    <div>
        <label for="country" class="label_control"> 
            Country
        </label>
        <div class="form_control" id="country">
            {{ form.country }}
        </div>
    </div>
    {{ form.submit() }}
</form>
</div>


{% endblock %}

So everything seems to run okay without an error but the record doesn't get added to the database. Any help would be appreciated.

Это было полезно?

Решение

You have two issues here. One is that your form is never validating, because it does not have the form.hidden_tag() anywhere and your not showing an error on the page. The following adds the token and a div for displaying any form errors if they occur.

The second issue is that you're never committing your db session to the database, thus your data would not get saved even if your form validated.

Form not validating and no error is shown:

In your form, try to add the {{ form.hidden_tag() }} after which your form should submit nicely. If you don't add that, the form will raise an error, as it's no longer valid XHTML.

<div class="container">
<form method="POST" action="/country">
    <div>
        <label for="country" class="label_control"> 
            Country
        </label>
        <div class="form_control" id="country">
            {{ form.hidden_tag() }}
            {{ form.country }}
        </div>
        <div class="form_errors">
           {{ form.errors }}
       </div>
    </div>
    {{ form.submit() }}
</form>
</div>

Data not being saved:

You're not calling db.session.commmit() anywhere, which is why the session is never committed to the database.

@main.route('/country', methods=['GET','POST'])
def show_CountryForm():
    form = CountryForm()
    print 'Form Values',form
    if form.validate_on_submit():
        ctry = Country(country=form.country.data)
        db.session.add(ctry)
        db.session.commit() # This saves the data.
        flash('The country has been added.')
        return redirect(url_for('chinese'))
    return render_template("country.html", form=form)
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top