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


i trying create blog using flask. every post can have multiple tags every tag associated multiple posts. created many-to-many relationship. questions how save multiple tags when creating new post. , since every post can have different number of tags how show in form? also, how can create new tags along post , use tags other posts? 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 view working on -

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

i sure there easy solution , complicating this, new web development, please help.

you can pull categories out of form getlist , add them post object. if have checkboxes following:

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

in view method can do:

categories_from_form = request.form.getlist('categories') # ['bar'] # create category objects form data categories = [category(title=title) title in categories_from_form]  post = post(request.form['title'], request.form['content'], request.form['slug'], request.form['published']) post.categories = categories # attach category objects post ... 

Comments

Popular posts from this blog

c++ - llvm function pass ReplaceInstWithInst malloc -

java.lang.NoClassDefFoundError When Creating New Android Project -

Decoding a Python 2 `tempfile` with python-future -