Flask无法重定向至指定图片详情页问题求助
解决Flask评论提交后重定向到特定图片页面的问题
我来帮你搞定这个重定向的问题!你当前的问题核心在于重定向时没有传递图片的ID参数,导致新加载的description页面无法获取到正确的图片ID,自然没法展示对应的图片。
问题分析
你现在的redirect(url_for('description'))只指定了路由函数,但没有把当前页面的photo_id传过去。这样重定向后,request.args.get('id')拿到的是None,查询不到对应的图片,所以页面无法正常展示目标图片。
修复方案
修改路由里的重定向代码,把photo_id作为参数传给url_for,让它生成带正确ID的URL:
@app.route('/description', methods=['GET', 'POST']) def description(): photo_id = request.args.get('id') photo = Photo.query.filter_by(id=photo_id).first() if form.validate_on_submit(): flash('Your comment posted successfully.') # 关键:添加id参数,确保重定向后能拿到正确的图片ID return redirect(url_for('description', id=photo_id)) return render_template('description.html', title='Description', photo=photo, form=form)
额外优化建议
为了避免用户手动输入无效ID导致页面出错,你可以加个判断:如果查询不到对应图片,就重定向到首页或者错误页面:
@app.route('/description', methods=['GET', 'POST']) def description(): photo_id = request.args.get('id') photo = Photo.query.filter_by(id=photo_id).first() # 如果找不到图片,重定向到首页(假设你有index路由) if not photo: flash('Requested photo not found!') return redirect(url_for('index')) if form.validate_on_submit(): flash('Your comment posted successfully.') return redirect(url_for('description', id=photo_id)) return render_template('description.html', title='Description', photo=photo, form=form)
这样修改后,用户提交评论后就会被正确重定向到原来的图片详情页,展示对应的图片内容了。
内容的提问来源于stack exchange,提问作者user9470055
相关产品推荐
相关产品推荐

