如何在Flask视图中使用多对多字段? [英] How to use many-to-many fields in Flask view?

查看:43
本文介绍了如何在Flask视图中使用多对多字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Flask创建博客.每个帖子可以具有多个标签,每个标签可以与多个帖子关联.因此,我建立了多对多关系.我的问题是在创建新帖子时如何保存多个标签.而且由于每个帖子可以具有不同数量的标签,我如何以表格形式显示它?另外,如何与帖子一起创建新标签,然后将这些标签与其他帖子一起使用?这是models.py-

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'])

我肯定有一个简单的解决方案,只是让事情复杂化了,但是我是Web开发的新手,所以请帮忙.

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

推荐答案

您可以使用 getlist 将类别从表单中拉出,并将其添加到Post对象.如果您有如下所示的复选框:

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
...

这篇关于如何在Flask视图中使用多对多字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆