Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python

Kyle Barney
Kyle Barney
9,081 Points

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. 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

# CREATE EVENT
@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?

Chris Freeman
Chris Freeman
Treehouse Moderator 68,167 Points

Are you getting any other errors or just are you just seeing the 200 message, but no save?

Kyle Barney
Kyle Barney
9,081 Points

I've been messing around with it more, and now I'm getting this:

peewee.InternalError
InternalError: (1054, u"Unknown column 'name' in 'field list'")

Traceback (most recent call last)
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1836, in __call__
return self.wsgi_app(environ, start_response)
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1820, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1403, in handle_exception
reraise(exc_type, exc_value, tb)
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1477, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1381, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1475, in full_dispatch_request
rv = self.dispatch_request()
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1461, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/usr/local/lib/python2.7/dist-packages/flask_login.py", line 792, in decorated_view
return func(*args, **kwargs)
File "/home/kylebarney/Applications/RecordWorthy/app.py", line 149, in create_event
date=form.date.data)
File "/usr/local/lib/python2.7/dist-packages/peewee.py", line 4289, in create
inst.save(force_insert=True)
File "/usr/local/lib/python2.7/dist-packages/peewee.py", line 4461, in save
pk_from_cursor = self.insert(**field_dict).execute()
File "/usr/local/lib/python2.7/dist-packages/peewee.py", line 3113, in execute
cursor = self._execute()
File "/usr/local/lib/python2.7/dist-packages/peewee.py", line 2535, in _execute
return self.database.execute_sql(sql, params, self.require_commit)
File "/usr/local/lib/python2.7/dist-packages/peewee.py", line 3339, in execute_sql
self.commit()
File "/usr/local/lib/python2.7/dist-packages/peewee.py", line 3185, in __exit__
reraise(new_type, new_type(*exc_args), traceback)
File "/usr/local/lib/python2.7/dist-packages/peewee.py", line 3331, in execute_sql
cursor.execute(sql, params or ())
File "/usr/local/lib/python2.7/dist-packages/pymysql/cursors.py", line 146, in execute
result = self._query(query)
File "/usr/local/lib/python2.7/dist-packages/pymysql/cursors.py", line 296, in _query
conn.query(q)
File "/usr/local/lib/python2.7/dist-packages/pymysql/connections.py", line 781, in query
self._affected_rows = self._read_query_result(unbuffered=unbuffered)
File "/usr/local/lib/python2.7/dist-packages/pymysql/connections.py", line 942, in _read_query_result
result.read()
File "/usr/local/lib/python2.7/dist-packages/pymysql/connections.py", line 1138, in read
first_packet = self.connection._read_packet()
File "/usr/local/lib/python2.7/dist-packages/pymysql/connections.py", line 906, in _read_packet
packet.check_error()
File "/usr/local/lib/python2.7/dist-packages/pymysql/connections.py", line 367, in check_error
err.raise_mysql_exception(self._data)
File "/usr/local/lib/python2.7/dist-packages/pymysql/err.py", line 120, in raise_mysql_exception
_check_mysql_exception(errinfo)
File "/usr/local/lib/python2.7/dist-packages/pymysql/err.py", line 115, in _check_mysql_exception
raise InternalError(errno, errorvalue)
InternalError: (1054, u"Unknown column 'name' in 'field list'")

1 Answer

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,167 Points

I mocked up your code to run (using scaffolding from the flask-social project). In debug, in addition to also see the Post 200 log message, I saw a runtime error when trying to create the event:

builtins.AttributeError
AttributeError: 'datetime.date' object has no attribute 'strip'

Looking at your create_event code, removing the.strip()` from the date field seems to fix the issue.

@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()  # NO strip() attribute
                            date=form.date.data
                            )
        flash("Event created!", "success")
        # return redirect(url_for('timeline'))
        return redirect(url_for('index'))
    # return render_template('userpages/event_create.html', form=form)
    return render_template('event_create.html', form=form)
Kyle Barney
Kyle Barney
9,081 Points

Yep, for some reason that wasn't coming through every time. I removed it just a bit ago. But I'm still getting the error. I just checked my db and don't see the 'name' column in the table, so I'm going to recreate the table and see if that fixes the issue.

Kyle Barney
Kyle Barney
9,081 Points

That did it. Looks like since I edited the model after the table was created the changes didn't migrate properly. Thanks for the assist.