def create_post(slug): """Create a new or edit an existing blog post""" next = request.values.get('next', '') post = None if slug: post = Post.query.filter_by(slug=slug).first() if slug and not post: flash('Invalid slug', 'error') return redirect(next) if request.method == 'GET': return render_template('admin/compose.html', post=post, categories=Category.query.all()) if request.method == 'POST': if request.form['action'] == 'Cancel': return redirect(next) title = request.form['title'] markup = request.form['markup'] tags = normalize_tags(request.form['tags']) comments_allowed = bool(request.values.get('comments_allowed', False)) visible = bool(request.values.get('visible', False)) #: Contains the ids of the categories categories = [] for name, id in request.form.iteritems(): if 'category-' in name: categories.append(id) if title == '': flash('You must provide a title', 'error') return render_template('admin/compose.html') elif request.form['action'] == 'Publish': post = Post(title, markup, comments_allowed, visible) post.tags = tags post.categories = categories db.session.add(post) db.session.commit() signals.post_created.send(post) flash('New post was successfully posted') return redirect(url_for('main.show_posts')) elif request.form['action'] == 'Update': post.title = title post.markup = markup post.comments_allowed = comments_allowed post.visible = visible post.tags = tags post.categories = categories db.session.commit() signals.post_updated.send(post) flash('Post was successfully updated') return redirect(url_for('main.show_post', slug=post.slug))
def test_tag_associations(self): """Test if categories and posts are correctly associated with each other""" self.clear_db() db.session.add(Category('cool')) db.session.add(Category('cooler')) db.session.commit() post1 = Post(title='t', markup='') post1.categories = [1] post2 = Post(title='t2', markup='') post2.categories = [1, 2] db.session.add(post1) db.session.add(post2) db.session.commit() assert_equal(Category.query.get(1).posts.count(), 2) # cool assert_equal(Category.query.get(2).posts.count(), 1) # cooler assert_equal(len(post1.categories), 1) assert_equal(post1.categories[0].name, 'cool') assert_equal(len(post2.categories), 2) assert_equal(post2.categories[0].name, 'cool') assert_equal(post2.categories[1].name, 'cooler')