How to use many-to-many fields in Flask view?

独自空忆成欢 提交于 2021-02-08 08:37:56

问题


I am trying to create a blog using Flask. Every post can have multiple tags also every tag could be associated with multiple posts. So I created a many-to-many relationship. My questions is how do i save multiple tags when creating a new post. And since every post can have different number of tags how do i show this is in the form? Also, how can i create new tags along with the post and then use those tags with other posts? This is models.py -

postcategory = db.Table('tags',
    db.Column('posts_id', db.Integer, db.ForeignKey('posts.id')),
    db.Column('categories_id', db.Integer, db.ForeignKey('categories.id'))
)

class Post(db.Model):
    __tablename__ = 'posts'
    id = db.Column(db.Integer, primary_key=True)     
    title = db.Column(db.String)
    content = db.Column(db.Text)
    slug = db.Column(db.String, unique=True)
    published = db.Column(db.Boolean, index=True)
    timestamp = db.Column(db.DateTime, index=True)
    categories = db.relationship('Category', secondary=postcategory, backref='posts' )

    def __init__(self, title, content):
        self.title = title
        self.content = content

class Category(db.Model):
    __tablename__ = 'categories'
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String, index=True)

This is the view i am working on -

def create_article():
    if request.method == 'POST':
        if request.form.get('title') and request.form.get('content') and request.form.get('slug') and request.form.get('published'):
            post = Post(request.form['title'], request.form['content'], request.form['slug'], request.form['published'])

I am sure there is a easy solution and i am just complicating this, but i am new to web development, so please help.


回答1:


You can pull the categories out of the form with getlist and add them to the Post object. If you have checkboxes like the following:

<form>
    <input type="checkbox" name="categories" value="foo">
    <input type="checkbox" name="categories" value="bar" checked>
</form>

In your view method you can just do:

categories_from_form = request.form.getlist('categories') # ['bar']
# create Category objects with the form data
categories = [Category(title=title) for title in categories_from_form]

post = Post(request.form['title'], request.form['content'], request.form['slug'], request.form['published'])
post.categories = categories # attach the Category objects to the post
...


来源:https://stackoverflow.com/questions/34828855/how-to-use-many-to-many-fields-in-flask-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!