I think the id below is equal to the user.id above but I don’t know how to get this value
过去多啦不再A梦2017-05-18 11:00:21
Thanks for the invitation. Just use the parameters of the view function directly.
http://flask.pocoo.org/docs/0...
迷茫2017-05-18 11:00:21
Thank you for the invitation. Here is an idea to use flask_wtf
to interact with front-end and back-end forms. To get started, you can see
http://flask123.sinaapp.com/a...
Here is a simple login example:
First, construct the form on the backend and define it in forms.py
:
from flask_wtf import Form
from wtforms import StringField, PasswordField, BooleanField, SubmitField
from wtforms.validators import Required, Length, Email, Regexp, EqualTo
#自定义的表单都要继承于flask_wtf中的Form表单
class LoginForm(Form):
email = StringField('登陆邮箱', validators=[Required(), Length(1, 64),
Email()])
password = PasswordField('密码', validators=[Required()])
remember_me = BooleanField('记住我')
submit = SubmitField('登陆')
So how to put this form on the web page? Let’s take a look at login.html
first:
{% extends "base.html" %}
<!-- 注意这里要导入bootstrap/wtf.html -->
{% import "bootstrap/wtf.html" as wtf %}
{% set active_page = "login" %}
{% block title %}登陆{% endblock %}
{% block page_content %}
<p class="container">
<p class="page-header" style="margin-top: 120px;">
<h1 class="white">登陆</h1>
</p>
<p class="col-md-4" >
<!-- 这里使用wtf.quick_form即可创建表单,那么form哪里来呢?看下面 -->
{{ wtf.quick_form(form) }}
<br>
<p>忘记密码? <a href="{{ url_for('auth.password_reset_request') }}">重置密码。</a></p>
<p>没有账号? <a href="{{ url_for('auth.register') }}">注册。</a></p>
</p>
</p>
{% endblock %}
So where does the form
in login.html
中的form
是哪里来的呢?让我们来看路由views.py
come from? Let’s look at routing views.py
from flask import render_template, redirect, request, url_for, flash
from .forms import LoginForm
from ..models import User
@auth.route('/login', methods=['GET', 'POST'])
def login():
#从forms.py中导入刚刚建好的 LoginForm()
form = LoginForm()
#【你要的答案在这里,当用户提交表单后会执行下列语句】
if form.validate_on_submit():
#用form.xxx.data即可获取数据,这里使用了form.email.data获取了用户输入的email进行查询
user = User.query.filter_by(email=form.email.data).first()
#如果查询到用户并且密码正确的话
if user is not None and user.verify_password(form.password.data):
#登陆用户,并重定向到之前的页面或主页
login_user(user, form.remember_me.data)
return redirect(request.args.get('next') or url_for('main.index'))
#否则提示用户用户名不对或密码不对
flash('Invalid username or password.')
#!!!这里要注意,第一次用户开进这个登陆界面的时候是直接执行下面这条语句的,要注意把form传入,jinja2才可以对表单进行渲染。
return render_template('auth/login.html', form=form)
It is also the content of the book "Flask Web Development: Practical Web Application Development Based on Python". I reviewed it again today~Haha, so if you want to learn Flask, I recommend reading this book~ Any questions? Welcome to continue to ask questions, thank you~~
phpcn_u15822017-05-18 11:00:21
Use request context
from flask import request
# ...
user = User.query.filter_by(User.id==request.args.get('id', 0))