Python Flask 构建微电影视频网站教程遇到的问题
本帖最后由 lgsp_Jim 于 2021-5-13 12:08 编辑按照视频教程,第73行查询所有tags报运行时错误,只要删除73行和第96行的引用,就不会报错。度不到解决方法,求大神给我解释下是为什么?如何解决。谢谢~~
forms.py
from flask import flash
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField, validators, ValidationError, FileField, TextAreaField, \
SelectField
from models import Admin, Tag
class LoginForm(FlaskForm):
""" 管理员登录表单 """
username = StringField(label='用户名', validators=, render_kw={
'class': 'form-control',
'placeholder': '请输入账号',
'required': 'required'
})
password = PasswordField(label='密码', validators=, render_kw={
'class': 'form-control',
'placeholder': '请输入密码',
'required': 'required'
})
submit = SubmitField(label='登录', render_kw={
'class': 'btn btn-primary btn-block btn-flat',
})
# def validate_username(self, field):
# username = field.data
# admin = Admin.query.filter_by(username=username).count()
# if admin == 0:
# flash('账号不存在!', 'danger')
# raise ValidationError('账号不存在!')
def validate(self):
result = super().validate()
username = self.username.data
password = self.password.data
if result:
try:
admin = Admin.query.filter_by(username=username).first()
if admin is None:
flash('账号不存在!', 'danger')
result = False
self.username.errors = ['账号不存在!']
elif not admin.check_password(password):
flash('密码错误!', 'danger')
result = False
self.password.errors = ['密码错误!']
except Exception as e:
flash('服务器忙,请联系管理员或稍后重试!', 'danger')
result = False
return result
class TagForm(FlaskForm):
name = StringField('标签名称', validators=[validators.DataRequired('标签名不能为空!'),
validators.length(min=1, max=128, message='标签名长度在1-128之间')], render_kw={
'class': 'form-control',
'placeholder': '请输入标签名称!',
'required': 'required'
})
submit = SubmitField(label='保存', render_kw={
'class': 'btn btn-primary',
})
def validate_name(self, field):
name = field.data
tag = Tag.query.filter_by(name=name).count()
if tag == 1:
flash('标签名已存在!', 'danger')
raise ValidationError('标签名已存在')
class MovieForm(FlaskForm):
tags = Tag.query.all()
name = StringField(label='片名', validators=, render_kw={
'class': 'form-control',
'placeholder': '请输入片名!'
})
url = FileField(label='文件', validators=)
info = TextAreaField(label='简介', validators=, render_kw={
'class': 'form-control',
'placeholder': '请输入简介!',
'row': 10
})
logo = FileField(label='封面', validators=)
star = SelectField(label='星级', validators=, render_kw={
'class': 'form-control',
}, coerce=int, choices=[(1, '1星'), (2, '2星'), (3, '3星'), (4, '4星'), (5, '5星')])
tag_id = SelectField(
label='标签',
validators=,
render_kw={
'class': 'form-control',
},
coerce=int,
choices=[(v.id, v.name) for v in tags])
area = StringField(label='地区', validators=, render_kw={
'class': 'form-control',
'placeholder': '请输入地区!'
})
movie_length = StringField(label='电影时长', validators=, render_kw={
'class': 'form-control',
'placeholder': '请输入电影时长!'
})
release_date = StringField(label='上映日期', validators=, render_kw={
'class': 'form-control',
'placeholder': '请输入上映日期!',
'id': 'input_release_time'
})
submit = SubmitField(label='保存', render_kw={
'class': 'btn btn-primary',
})
views.py
from flask import Blueprint, render_template, redirect, url_for, flash, session, request
from admin.forms import LoginForm, TagForm, MovieForm
from functools import wraps
from conf import Config
from models import db, Tag
admin = Blueprint('admin', __name__,
template_folder='templates',
static_folder='../static/admin')
def admin_login_req(func):
@wraps(func)
def decorated_function(*args, **kwargs):
if 'admin' not in session:
return redirect(url_for('admin.login', next=request.url))
return func(*args, **kwargs)
return decorated_function
@admin.route('/')
@admin_login_req
def index():
return render_template('admin_index.html')
# 登录
@admin.route('/login/', methods=['GET', 'POST'])
def login():
form = LoginForm()
if form.validate_on_submit():
data = form.data
# admin = Admin.query.filter_by(username=data['username']).first()
# if not admin.check_password(data['password']):
# flash('密码错误', 'danger')
# return redirect(url_for('admin.login'))
session['admin'] = data['username']
return redirect(request.args.get('next') or url_for('admin.index'))
return render_template('admin_login.html', form=form)
# 退出
@admin.route('/logout/', methods=['GET'])
@admin_login_req
def logout():
session.pop('admin', None)
return redirect(url_for('admin.login'))
# 修改密码
@admin.route('/edit_password/', methods=['GET', 'POST'])
@admin_login_req
def edit_password():
return render_template('admin_edit_password.html')
# 添加标签
@admin.route('/tag_add/', methods=['GET', 'POST'])
@admin_login_req
def tag_add():
form = TagForm()
if form.validate_on_submit():
name = form.name.data
try:
tag = Tag(name=name)
db.session.add(tag)
db.session.commit()
flash('添加成功', 'success')
return redirect(url_for('admin.tag_add'))
except Exception as e:
flash('服务器忙,请联系管理员或稍后重试!', 'danger')
return redirect(url_for('admin.tag_add'))
return render_template('admin_tag_add.html', form=form)
# 编辑标签
@admin.route('/tag_edit/<int:tag_id>', methods=['GET', 'POST'])
@admin_login_req
def tag_edit(tag_id):
form = TagForm()
tag_obj = Tag.query.get(tag_id)
if form.validate_on_submit():
name = form.name.data
tag_count = Tag.query.filter_by(name=name).count()
if tag_obj.name != name and tag_count == 1:
flash('标签已存在', 'warning')
return redirect(url_for('admin.tag_edit'))
try:
tag_obj.name = name
db.session.add(tag_obj)
db.session.commit()
flash('标签修改成功', 'success')
return redirect(url_for('admin.tag_list', page=1))
except Exception as e:
flash('服务器忙,请联系管理员或稍后重试!', 'danger')
return redirect(url_for('admin.tag_list', page=1))
return render_template('admin_tag_edit.html', form=form, tag_obj=tag_obj)
# 标签列表
@admin.route('/tag_list/<int:page>/', methods=['GET'])
@admin_login_req
def tag_list(page=1):
page_data = Tag.query.paginate(page, per_page=Config.PER_PAGE)
return render_template('admin_tag_list.html', page_data=page_data)
# 删除标签
@admin.route('/tag_del/<int:tag_id>/', methods=['GET'])
@admin_login_req
def tag_del(tag_id):
tag_obj = Tag.query.filter_by(id=tag_id).first()
if not tag_obj:
flash('查询不到标签,请刷新后重试!', 'warning')
return redirect(url_for('admin.tag_list', page=1))
else:
db.session.delete(tag_obj)
db.session.commit()
flash('标签:{},删除成功!'.format(tag_obj.name), 'success')
return redirect(url_for('admin.tag_list', page=1))
# 添加电影
@admin.route('/movie_add/', methods=['GET', 'POST'])
@admin_login_req
def movie_add():
form = MovieForm()
return render_template('admin_movie_add.html', form=form)
# 电影列表
@admin.route('/movie_list/', methods=['GET'])
@admin_login_req
def movie_list():
return render_template('admin_movie_list.html')
https://www.cnblogs.com/haiton/p/11101476.html 自行对照吧,代码太多 懒得看 本帖最后由 lgsp_Jim 于 2021-5-13 11:59 编辑
sunzhiqiang 发表于 2021-5-13 07:55
https://www.cnblogs.com/haiton/p/11101476.html 自行对照吧,代码太多 懒得看
应该不是你找的那个,我已经在app.py初始化了,不然我views.py和forms.py第38、66行不可能操作数据库。
from flask import Flask, render_template
import conf
from admin.views import admin
from home.views import home
from models import db
app = Flask(__name__)
# 从配置文件加载配置
app.config.from_object(conf.Config)
# 数据库初始化
db.init_app(app)
# 注册蓝图
app.register_blueprint(admin, url_prefix='/admin')
app.register_blueprint(home, url_prefix='/')
@app.errorhandler(404)
def page_not_found(error):
return render_template('home_404.html'), 404
解决了,加个初始化方法将查询到的数据再赋值给表单
页:
[1]