Python 在烧瓶中过帐图像未保存到数据库
我正在尝试在我的flask项目中创建一个新页面,我可以使用它在主页上发布一篇带有标题和图像的新闻文章。我已经成功地发布了标题和内容,但图像没有保存 路线:Python 在烧瓶中过帐图像未保存到数据库,python,flask,Python,Flask,我正在尝试在我的flask项目中创建一个新页面,我可以使用它在主页上发布一篇带有标题和图像的新闻文章。我已经成功地发布了标题和内容,但图像没有保存 路线: @app.route("/news", methods=['GET', 'POST']) @login_required def home_news(): form = AddNewsForm() if form.validate_on_submit():
@app.route("/news", methods=['GET', 'POST'])
@login_required
def home_news():
form = AddNewsForm()
if form.validate_on_submit():
picture_file = form.picture.data
news = News(image_file=picture_file, title=form.title.data, content=form.content.data, author=current_user)
db.session.add(news)
db.session.commit()
flash('News has been added!', 'success')
return redirect(url_for('home'))
return render_template('home_news.html', form=form)
表格:
型号:
class News(db.Model):
id = db.Column(db.Integer, primary_key=True)
image_file = db.Column(db.String(20), nullable=False, default='default.jpg')
title = db.Column(db.String(100), nullable=False)
date_posted = db.Column(db.DateTime, nullable=False, default=datetime.utcnow )
content = db.Column(db.Text, nullable=False)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
def __repr__(self):
return f"Post('{ self.image_file}', { self.title}', '{ self.content}', '{ self.date_posted}')"
模板:
{% block content %}
<div class="new-list">
<h1>Latest news</h1>
{% for new in news.items %}
<article class="media content-section">
<div class="media-body">
<div class="article-metadata">
{{ new.author.username }}
</div>
<h2>{{ new.title }}</h2>
<img class="rounded-circle account-img" src="{{ new.image_file }}">
<p class="article-content">{{ new.content }}</p>
</div>
</article>
{% endfor %}
</div>
{% endblock content %}
{%block content%}
最新消息
{news.items%中的新项目为%s}
{{new.author.username}
{{new.title}}
{{new.content}
{%endfor%}
{%endblock内容%}
如果我不添加一张默认图片,我想让它发布一张默认图片,这样只有帐户用户“admin”可以发布到它,但是我一直坚持只获取它来保存图片,其余的我都不知道
{% block content %}
<div class="new-list">
<h1>Latest news</h1>
{% for new in news.items %}
<article class="media content-section">
<div class="media-body">
<div class="article-metadata">
{{ new.author.username }}
</div>
<h2>{{ new.title }}</h2>
<img class="rounded-circle account-img" src="{{ new.image_file }}">
<p class="article-content">{{ new.content }}</p>
</div>
</article>
{% endfor %}
</div>
{% endblock content %}