def category_edit(cat_id): category = Category.query.get_or_404(cat_id) error_fields = [] if request.method == 'POST': name = request.form['name'].strip() if len(name) <= 0: error_fields.append('name') slug = request.form['slug'].strip() if len(slug) <= 0: # generate a new slug if none is provided slug = slugify(name) published = request.form.get('published', False) if published is not False: published = True if len(error_fields) <= 0: if slug != category.slug: # if slug has changed, ensure it is unique while Category.query.filter_by(slug=slug).count() > 0: slug += '-' category.name = name category.slug = slug category.published = published try: db.session.commit() except: db.session.rollback() raise cache.set('blog_categories', list_categories()) flash("Category saved.") return redirect(url_for('admin.categories')) elif request.method == 'DELETE': db.session.delete(category) try: db.session.commit() except: db.session.rollback() raise cache.set('blog_categories', list_categories()) return jsonify({ '_csrf_token': app.jinja_env.globals['csrf_token'](), }) return render_template('admin/category_edit.html', category=category, error_fields=error_fields)
def category_add(): error_fields = [] if request.method == 'POST': name = request.form['name'].strip() if len(name) <= 0: error_fields.append('name') published = request.form.get('published', False) if published is not False: published = True if len(error_fields) <= 0: slug = slugify(name) # ensure slug is unique, add - until it is while Category.query.filter_by(slug=slug).count() > 0: slug += '-' db.session.add(Category(name, slug, published)) db.session.commit() cache.set('blog_categories', list_categories()) flash("Category added.") return redirect(url_for('admin.categories')) return render_template('admin/category_add.html', error_fields=error_fields)