I'm trying to create an image gallery related to parent model Article
. I have two models, one to store uploaded files and another to store posted articles linked by image_shots.articles.id
.
Here are my models:
class Media(db.Model):
__tablename__ = 'media'
id = db.Column(db.Integer, primary_key=True)
caption = db.Column(db.String(500))
article = db.Column(db.Integer, db.ForeignKey('articles.id'), index=True)
posted_date = db.Column(db.DateTime)
def __init__(self, **kwargs):
super(Media, self).__init__(**kwargs)
class Article(db.Model):
__tablename__ = 'articles'
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(400))
body = db.Column(db.Text)
updated_on = db.Column(db.DateTime)
view_count = db.Column(db.Integer)
image_shots = db.relationship("Media", backref="articles")
def __init__(self, **kwargs):
super(Article, self).__init__(**kwargs)
Here is my form:
from flask_wtf import Form, validators
from wtforms import StringField, TextAreaField
from wtforms.validators import DataRequired, Length
class ArticleForm(Form):
title = StringField('Title', validators=[DataRequired(), Length(1, 64), ])
description = TextAreaField(u'Description', [validators.optional(), validators.length(max=200)])
file = FileField()
Here is my view:
@articles.route('/new', methods=['GET', 'POST'])
def articles():
form = ArticleForm()
articles = [title for title, in db.session.query(Article)]
if request.method == 'POST'and form.validate_on_submit():
article = Article(title=form.name.data)
db.session.add(article)
db.session.commit()
flash(message='Article successfully added')
return redirect(url_for('articles.index'))
elif request.method == 'GET':
articles = [title for title, in db.session.query(Article)]
return render_template('front/articles.html', articles=articles, form=form)
With this, I'm able to save the posted article, but I'm still confused on how to get the uploaded files and save then in their own model with articles.id
as foreign key.
little detail, I needed to upload multiple files which form the image gallery in the same article form. How can they be linked?