简体   繁体   中英

Flask App Not Posting to Database

I can't seem to get this form to post data to my database. I'm working in the Flask framework for Python with the Peewee ORM. When I submit the form, I see a POST event execute (see below), but nothing is written to the database.

[21/Nov/2015 04:21:47] "POST /create-event HTTP/1.1" 200 -

I know the database connection itself is good because another write function is working. Below is the code along with an indication of which file it is in.

app.py

@app.route('/create-event', methods=('GET', 'POST'))
@login_required
def create_event():
    form = forms.EventForm()
    if form.validate_on_submit():
        models.Event.create(user=g.user.id,
                            name=form.name.data.strip(),
                            description=form.description.data.strip(),
                            date=form.date.data.strip()
                            )
        flash("Event created!", "success")
        return redirect(url_for('timeline'))
    return render_template('userpages/event_create.html', form=form)

forms.py

class EventForm(Form):
    name = StringField("Event Name", validators=[DataRequired()])
    description = TextAreaField("Description", validators=[DataRequired()])
    date = DateField("Date", validators=[DataRequired()])

models.py

class Event(Model):
    timestamp = DateTimeField(default=datetime.datetime.now)
    user = ForeignKeyField(
        rel_model=User,
        related_name='events'
    )
    name = CharField()
    description = TextField()
    date = DateField()

    class Meta:
        database = DATABASE
        order_by = ('-timestamp',)

event_create.html

{% extends "layout.html" %}
{% from 'macros.html' import render_field %}

{% block content %}

<h1>Create New Event</h1>

<form method="POST" action="" class="form">
    {{ form.hidden_tag() }}
    {% for field in form %}
        {{ render_field(field) }}
    {% endfor %}
    <button type="submit" id="submit">Create</button>
</form>

{% endblock %}

Any ideas?

Bad form to answer my own question, perhaps, but it looks like the main problem was that I had edited my model after the event table had already been created and the changes didn't apply properly. Deleting and recreating the table was what was needed.

The other problem is that you can't call .strip() on this date field.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM