简体   繁体   中英

python flask board - Why Can't I write?

What I want to make is a 'flask board'. I thought it would be very simple. I put up the server, and I can 'register' and 'login'. I'm trying to 'write' the same way, but it's not working. According to the error message, the problem is the 'title', but I've already defined it. What's the problem? please, help me:(:( I'll wait for your answer.

Flask 1.0.2, Python 3.7.3, Flask-SQLAlchemy, 'register' and 'login':working, "write":400 error

class User(db.Model):
    __table_name__ = 'user'
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True, nullable=False)
    password = db.Column(db.String(80), nullable=False)`

class post(db.Model):
    __table_name__ = 'post'
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(120), nullable=False)
    content = db.Column(db.Text, nullable=False)
    #date_posted = db.Column(db.DateTime, default=datetime.utcnow())
    #user_id = db.Column(db.Integer, db.ForeignKey('user_id'))`

def __init__(self, username, password, title, content):
    self.username = username
    self.password = password
    self.title = title
    self.content = content

@app.route('/register/', methods=['GET', 'POST'])
def register():
    if request.method == 'POST':
        new_user = User(username=request.form['username'],password=request.form['password'])
        db.session.add(new_user)
        db.session.commit()
        return render_template('login.html')
    return render_template('register.html')`

@app.route('/write', methods = ['GET', 'POST'])
def write():
    if request.method == 'POST':
      if not request.form['title'] or not request.form['content']:
        return "<script>alert('Please enter all the fields'); location.href='/write';</script>"
      else:
        post = post(title=request.form['title'], content=request.form['content'])         

        db.session.add(post)
        db.session.commit()
        return "<script>alert('Success!'); location.href='/'; </script>"
    return render_template('write.html')

write.html

<form action = "/write" method = "post">
     <label for = "title">Title</label><br>
     <input type = "text" name = "title" placeholder = "title" /><br>
     <label for = "content">content</label><br>
     <textarea name = "content" placeholder = "content"></textarea><br>
     <input type = "submit" value = "Submit" />
</form>

error message

werkzeug.exceptions.BadRequestKeyError
werkzeug.exceptions.HTTPException.wrap.<locals>.newcls: 400 Bad Request: KeyError: 'title'

Traceback (most recent call last)
File "C:\Users\nGle\AppData\Local\Programs\Python\Python37-32\lib\site-packages\flask\app.py", line 2309, in __call__
return self.wsgi_app(environ, start_response)
File "C:\Users\nGle\AppData\Local\Programs\Python\Python37-32\lib\site-packages\flask\app.py", line 2295, in wsgi_app
response = self.handle_exception(e)
File "C:\Users\nGle\AppData\Local\Programs\Python\Python37-32\lib\site-packages\flask\app.py", line 1741, in handle_exception
reraise(exc_type, exc_value, tb)
File "C:\Users\nGle\AppData\Local\Programs\Python\Python37-32\lib\site-packages\flask\_compat.py", line 35, in reraise
raise value
File "C:\Users\nGle\AppData\Local\Programs\Python\Python37-32\lib\site-packages\flask\app.py", line 2292, in wsgi_app
response = self.full_dispatch_request()
File "C:\Users\nGle\AppData\Local\Programs\Python\Python37-32\lib\site-packages\flask\app.py", line 1815, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Users\nGle\AppData\Local\Programs\Python\Python37-32\lib\site-packages\flask\app.py", line 1718, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "C:\Users\nGle\AppData\Local\Programs\Python\Python37-32\lib\site-packages\flask\_compat.py", line 35, in reraise
raise value
File "C:\Users\nGle\AppData\Local\Programs\Python\Python37-32\lib\site-packages\flask\app.py", line 1813, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Users\nGle\AppData\Local\Programs\Python\Python37-32\lib\site-packages\flask\app.py", line 1799, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "C:\Python27\app.py", line 103, in write
if not request.form['title'] or not request.form['content']:
File "C:\Users\nGle\AppData\Local\Programs\Python\Python37-32\lib\site-packages\werkzeug\datastructures.py", line 442, in __getitem__
raise exceptions.BadRequestKeyError(key)
werkzeug.exceptions.HTTPException.wrap.<locals>.newcls: 400 Bad Request: KeyError: 'title'

Use

if not request.form.get('title') or not request.form.get('content'):

Instead of

if not request.form['title'] or not request.form['content']:

using request.form.get('title') will throw 'None' in place of '400 Bad Request' if the key does not exist.

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