1

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.

doctorsherlock
  • 1,334
  • 4
  • 19
  • 41

1 Answers1

0

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
...
jumbopap
  • 3,969
  • 5
  • 27
  • 47
  • Then you should query for the category and add it to the `categories` list of ORM objects. Here's a way to `get_or_create` a model instance. http://stackoverflow.com/a/6078058/2178164 – jumbopap Jan 16 '16 at 20:48