예제 #1
0
def category():
    form = CategoryForm()

    if request.method == 'GET':
        categorys = Category.query.all()
        return render_template('back/category.html',
                               categorys=categorys,
                               form=form)
    if request.method == 'POST':
        if form.validate_on_submit():
            category = Category()
            category.c_name = form.data.get('name')
            category.nickname = form.data.get('nickname')
            category.keywords = form.data.get('keywords')
            category.save()
            categorys = Category.query.all()
            return render_template('back/category.html',
                                   message='添加成功',
                                   categorys=categorys,
                                   form=form)
        # errors = form.errors
        categorys = Category.query.all()
        return render_template('back/category.html',
                               message='添加有误',
                               categorys=categorys,
                               form=form)
예제 #2
0
def index():
    userform = AddUserForm()
    categoryform = CategoryForm()
    if userform.validate_on_submit():
        user = User(name=userform.name.data, email=userform.email.data)
        user.set_password(userform.password.data)
        db.session.add(user)
        db.session.commit()
        flash('User registration successful')
        return redirect(url_for('index'))

    if categoryform.validate_on_submit():
        cat = Category(title=categoryform.title.data)
        db.session.add(cat)
        db.session.commit()
        flash('New Category added successful')
        return redirect(url_for('index'))

    totalusers = db.session.query(User).count()
    totalcategory = db.session.query(Category).count()
    totalposts = db.session.query(Post).count()

    return render_template('Adminindex.html',
                           title='Admin Panel',
                           admin='admin',
                           userform=userform,
                           categoryform=categoryform,
                           totalusers=totalusers,
                           totalcategory=totalcategory,
                           totalposts=totalposts)
예제 #3
0
def add_category(user_id, book_id):
    rating_form = RatingForm()
    comment_form = CommentForm()
    category_form = CategoryForm()
    book = Book.query.get(book_id)

    if category_form.validate_on_submit():
        ub = User_Book.query.filter_by(user_id=user_id,
                                       book_id=book_id).first()
        if ub:
            ub.category = category_form.category.data
        else:
            ub = User_Book(user_id=user_id,
                           book_id=book_id,
                           category=category_form.category.data)
            db.session.add(ub)
        db.session.commit()
        return redirect(url_for('book', book_id=book_id))

    return render_template('book.html',
                           title=book.title,
                           GENRES=GENRES,
                           book=book,
                           rating_form=rating_form,
                           comment_form=comment_form,
                           category_form=category_form)
예제 #4
0
def category_change(id):
    form = CategoryForm()

    if request.method == 'GET':
        # 获取对象,渲染页面
        category = Category.query.filter(Category.id == id).first()
        return render_template('back/category2.html',
                               category2=category,
                               form=form)
    if request.method == 'POST':
        # 修改数据
        if form.validate_on_submit():
            category = Category.query.filter(Category.id == id).first()
            category.c_name = form.data.get('name')
            category.nickname = form.data.get('nickname')
            category.keywords = form.data.get('keywords')
            category.save()
            categorys = Category.query.all()
            return render_template('back/category.html',
                                   categorys=categorys,
                                   message='修改成功',
                                   form=form)
        # errors = form.errors
        return render_template('back/category2.html',
                               message='添加有误',
                               form=form)

    if request.method == 'DELETE':
        # 实现删除栏目
        category = Category.query.filter(Category.id == id).first()
        category.delete()
        # categorys = Category.query.all()
        data = {'code': 200, 'msg': '删除成功'}
        return jsonify(data)
예제 #5
0
파일: admin.py 프로젝트: 0akarma/0aK
def new_category():
    form = CategoryForm()
    if form.validate_on_submit():
        category = Category(cname=form.name.data)
        db.session.add(category)
        db.session.commit()
        flash('Category newed.', 'success')
        return redirect(url_for('.manage_post'))
    return render_template('admin/new_category.html', form=form)
예제 #6
0
파일: admin.py 프로젝트: redsnowc/odst
def new_category():
    form = CategoryForm()
    if form.validate_on_submit():
        with db.auto_commit():
            name = form.name.data
            db.session.add(Category(name=name))
        flash('分类创建成功', 'success')
        return redirect(url_for('web.manage_categories'))
    return render_template('admin/new_category.html', form=form)
예제 #7
0
def edit_category(category_id):
    form = CategoryForm()
    category = Category.query.get_or_404(category_id)
    if form.validate_on_submit():
        category.name=form.name.data
        db.session.commit()
        flash('修改分类成功')
        return redirect(url_for('.manage_category'))
    form.name.data = category.name
    return render_template('admin/edit_category.html', form=form)
예제 #8
0
def createCategory():
    category_form = CategoryForm()
    if request.method == 'POST' and category_form.validate_on_submit():
        category = Category(name=category_form.data['category_name'],
                            user_id=session.get('user_id'))
        db.session.add(category)
        db.session.commit()
        flash('Category created successfully', 'success')
        return redirect(
            url_for('catalog.viewCategory', category_name=category.name))
    return render_template('create_category.html', category_form=category_form)
예제 #9
0
파일: admin.py 프로젝트: redsnowc/odst
def edit_category(category_id):
    form = CategoryForm()
    category = Category.query.get_or_404(category_id)
    if category.id == 1:
        flash('默认分类不能修改!', 'warning')
        return redirect(url_for('web.index'))
    if form.validate_on_submit():
        with db.auto_commit():
            category.name = form.name.data
        flash('分类更新成功', 'success')
        return redirect(url_for('web.manage_categories'))
    form.name.data = category.name
    return render_template('admin/edit_category.html', form=form)
예제 #10
0
def add_category():
    form = CategoryForm()
    if not form.validate_on_submit():
        flash(list(form.errors.values())[0])
        return redirect(url_for('admin.categories'))

    if Category().check_category(request.form.get('category')):
        flash('Category already exists. Please try again')
        return redirect(url_for('admin.categories'))

    Category(cat=request.form.get('category')).add()

    return redirect(url_for('admin.categories'))
예제 #11
0
def admin_categories():
    category_form = CategoryForm()

    if request.method == 'POST' and category_form.validate_on_submit():
        category = Category(name=request.form['category_name'])

        db.session.add(category)
        db.session.commit()
        db.session.flush()
        flask.flash('Your category has been created', 'success')

    return flask.render_template(Theme.get_template(page='admin_categories'),
                                 manager=ModelManager, form=category_form)
예제 #12
0
파일: admin.py 프로젝트: goodxue/flask_web
def edit_category(category_id):
    form = CategoryForm()
    category = Category.query.get_or_404(category_id)
    if category.id == 1:
        flash('You can not edit the default category.', 'warning')
        return redirect(url_for('web.index'))
    if form.validate_on_submit():
        category.name = form.name.data
        db.session.commit()
        flash('Category updated.', 'success')
        return redirect(url_for('.manage_category'))
    form.name.data = category.name
    return render_template('admin/edit_category.html', form=form)
예제 #13
0
def process_category_form(request):
    category_form = CategoryForm(prefix="category_form")

    # Check whether the category form is for a project or subproject
    project_id = category_form.project_id.data
    subproject_id = 0
    if category_form.subproject_id.data:
        subproject_id = category_form.subproject_id.data

    # Remove category
    if category_form.remove.data:
        Category.query.filter_by(id=category_form.id.data).delete()
        db.session.commit()
        flash(
            '<span class="text-default-green">Categorie "%s" is verwijderd</span>'
            % (category_form.name.data))
        return return_redirect(project_id, subproject_id)

    # Update or save category
    if category_form.validate_on_submit():
        category = Category.query.filter_by(id=category_form.id.data)
        if len(category.all()):
            category.update({'name': category_form.name.data})
            db.session.commit()
            flash(
                '<span class="text-default-green">Categorie is bijgewerkt</span>'
            )
        else:
            try:
                if subproject_id:
                    category = Category(name=category_form.name.data,
                                        subproject_id=subproject_id)
                else:
                    category = Category(name=category_form.name.data,
                                        project_id=project_id)
                db.session.add(category)
                db.session.commit()
                flash('<span class="text-default-green">Categorie '
                      f'{category_form.name.data} is toegevoegd</span>')
            except IntegrityError as e:
                db.session().rollback()
                app.logger.error(repr(e))
                flash(
                    '<span class="text-default-red">Categorie toevoegen mislukt: naam '
                    f'"{category_form.name.data}" bestaat al, kies een '
                    'andere naam<span>')

        # Redirect back to clear form data
        return return_redirect(project_id, subproject_id)
    else:
        flash_form_errors(category_form, request)
예제 #14
0
def edit_category(category_id):
    form = CategoryForm()
    category = Category.query.get_or_404(category_id)
    if category.id == 1:
        flash('您无法编辑默认分类。', 'warning')
        return redirect(url_for('blog.index'))
    if form.validate_on_submit():
        category.name = form.name.data
        db.session.commit()
        flash('类别已更新。', 'success')
        return redirect(url_for('.manage_category'))

    form.name.data = category.name
    return render_template('admin/edit_category.html', form=form)
예제 #15
0
파일: views.py 프로젝트: JMourisca/Tutorial
def category():
    form = CategoryForm()
    if form.validate_on_submit():
        category_slug = slugify(form.category.data)
        category = Category(category=form.category.data,
                            timestamp=datetime.utcnow(),
                            author=g.user,
                            category_slug=category_slug)
        db.session.add(category)
        db.session.commit()
        flash("Category created!")
    else:
        flash("Nothing happened.")
    return redirect(url_for("index"))
예제 #16
0
def deleteCategory(category_name, **kwds):
    category = kwds['category']
    category_form = CategoryForm()
    category_form.category_name.data = category.name
    if request.method == 'POST' and category_form.validate_on_submit():
        for item in category.items:
            db.session.delete(item)
        db.session.delete(category)
        db.session.commit()
        flash('Category deleted successfully', 'success')
        return redirect(url_for('catalog.recentItems'))
    return render_template('delete_category.html',
                           category_form=category_form,
                           category=category)
예제 #17
0
def editCategory(category_name, **kwds):
    category = kwds['category']
    category_form = CategoryForm()
    if request.method == 'POST' and category_form.validate_on_submit():
        category.name = category_form.data['category_name']
        db.session.add(category)
        db.session.commit()
        flash('Category edited successfully', 'success')
        return redirect(
            url_for('catalog.viewCategory', category_name=category.name))
    category_form.category_name.data = category.name
    return render_template('edit_category.html',
                           category_form=category_form,
                           category=category)
예제 #18
0
def add_category():
    form=CategoryForm()
    if form.validate_on_submit():
        category=Category(
            category=((form.category.data).lower()).capitalize(),
            user_id=current_user.id
            )
        # category=(category.lower()).capitalize()
        db.session.add(category)
        sb.session.commit()
        flash('Category added!', 'info')

        return redirect(url_for('categories'))

    return render_template('categories.html', categories=categories, form=form)
예제 #19
0
def new_category():
    if g.user.permission >= 1:
        return redirect(url_for('admin.index'))

    form = CategoryForm()

    if form.validate_on_submit():
        name = form.name.data
        cat = Category()
        cat.name = name
        db.session.add(cat)
        db.session.commit()
        return redirect(url_for('admin.index'))

    return render_template('admin/category.html', form=form)
예제 #20
0
파일: admin.py 프로젝트: Shindler7/libpraks
def db_headings():
    """
    Просмотр и добавление категорий и типов.
    """

    if not current_user.isadmin:
        redirect(url_for('index'))

    category = Category.manager.get_all()
    types = Types.manager.get_all()

    form_c = CategoryForm(request.form or None, prefix='category')
    form_t = TypesForm(request.form or None, prefix='types')

    if request.method == 'POST':

        if request.form.get('category-name', False) \
                and form_c.validate_on_submit():

            try:
                Category.manager.add(name=form_c.name.data,
                                     f_name=form_c.fname.data)

            except SQLAlchemyError as err:
                flash(f'Ошибка сохранения категории: {err}', category='danger')
            else:
                flash('Категория успешно добавлена!', category='success')
                return redirect(url_for('db_headings'))

        if request.form.get('types-name', False) \
                and form_t.validate_on_submit():

            try:
                Types.manager.add(name=form_t.name.data,
                                  f_name=form_t.fname.data)
            except SQLAlchemyError as err:
                flash(f'Ошибка сохранения типа данных: {err}',
                      category='danger')
            else:
                flash('Новый тип успешно добавлен!', category='success')
                return redirect(url_for('db_headings'))

    return render_template('dbpanel/db_headings.html',
                           category=category,
                           types=types,
                           form_c=form_c,
                           form_t=form_t)
예제 #21
0
def addCategory():
    if current_user.is_authenticated:
        form = CategoryForm()
        hasCategory = Category.query.filter_by(name=form.name.data).first()
        if hasCategory is not None:
            flash('Category is already exists.')
            return render_template('category/addCategory.html', title='Add Category', form=form)

        if form.validate_on_submit():
            category = Category(name=form.name.data, description=form.description.data)
            db.session.add(category)
            db.session.commit()
            flash('Successfully Added the Category!')
            return redirect(url_for('category'))
        elif form.cancel.data == True:
            return redirect(url_for('category'))
    return render_template('category/addCategory.html', title='Add Category', form=form)
예제 #22
0
def category_add_edit(category_id=None):
    if 'authenticated' not in session:
        return redirect('/login')
    form = CategoryForm()

    if form.validate_on_submit():  # it's submit!
        form.save_to_db()
        return redirect('/categories')
    else:  # either edit or add
        if category_id:  # populate first for edit
            form.load_from_db(category_id)

    return render_template('category_edit_or_add.html',
                           page='category_edit_or_add',
                           title='Άρθρα',
                           cdn=cdn,
                           form=form)
예제 #23
0
def category_new():
    """Nuova categoria"""
    form = CategoryForm()
    error = None
    descr = ''
    if form.validate_on_submit():
        descr = form.descr.data.lower()
        cat = Category.query.filter_by(descr=descr).first()
        if cat:
            error = 'Categoria già presente!'
        else:
            db.session.add(Category(descr))
            db.session.commit()
            return redirect(url_for('main.category'))

    return render_template("category_new.html",
                           form=form,
                           error=error,
                           titolo='Nuova Categoria',
                           descr=descr)
예제 #24
0
def update_category(transaction_id):

    transaction = Transaction.query.filter_by(id=transaction_id).first()

    form = CategoryForm()

    if form.validate_on_submit():

        category = form.category.data
        transaction.category = category
        transaction.customized = True
        db.session.commit()

        flash("Updated transaction category to {}".format(category))

        return redirect(url_for('overview'))

    return render_template('category.html',
                           form=form,
                           categories=categories,
                           transaction=transaction)
예제 #25
0
def tag(id):
    print("tag request:", request)

    entry = Entry.query.filter_by(id=id).first()
    print('entry:', entry.id, entry.name, entry.tag_id)
    entryTag = Tag.query.filter_by(id=entry.tag_id).first()

    # TODO: not sure how this happened, need to invistagate
    if entryTag == None:
        entryTag = Tag.query.filter_by(category='UNCATEGORIZED').first()

    print(entryTag.category, entryTag.subCategory)

    form = CategoryForm()
    form.description.data = entry.description

    tags = Tag.query.all()

    # create a unique list of categories
    tagList = [tag.category for tag in tags]
    tagList = list(set(tagList))
    tagList.sort()
    print('cat:', tagList)

    # TODO should i use the actual id? (value, label)
    #categoryList = list((map(lambda x: x.name, categories)))
    categoryList = [
        (tag, tag) for tag in tagList
    ]  # id must be a str? else validate_on_submit will be False? why or use coerce=int?
    form.category.choices = categoryList

    # create the sub cat list for the entrie's tag
    tags = Tag.query.filter_by(id=entry.tag_id).all()
    print('tags:', tags)
    tagList = [tag.subCategory for tag in tags]
    tagList = list(set(tagList))
    tagList.sort()
    print('sub:', tagList)

    subCategoryList = [(tag, tag) for tag in tagList]
    print(subCategoryList)
    form.subCategory.choices = subCategoryList

    if request.method == 'GET':
        print('GET')
        print(form.category.data)
        form.category.data = entryTag.category
        form.subCategory.data = entryTag.subCategory

    elif request.method == 'POST':
        print('POST', form.submit.data, form.validate_on_submit())
        print('form.submit.data: Name:{}, Category:{}*, Sub:{}*, Desc:{}*'.
              format(form.name.data, form.category.data, form.subCategory.data,
                     form.description.data))
        #if form.validate_on_submit():
        # The user pressed the "Submit" button
        #print('validate_on_submit')
        if form.submit.data:
            print('form.submit.data:', form.name.data, form.category.data,
                  form.subCategory.data)
            rows_changed = Entry.query.filter_by(name=entry.name).update(
                dict(tag_id=form.subCategory.data))
            print(rows_changed)
            db.session.commit()

            # update tagNameMapping
            # Does it already exist
            tagMapping = TagNameMapping.query.filter_by(
                name=entry.name).first()

            # add mapping if no row in table with this description
            if tagMapping is None:
                tagMapping = TagNameMapping(name=entry.name,
                                            tag=entry.displayTag())
                db.session.add(tagMapping)
            # else update existing mapping
            else:
                rows_changed = TagNameMapping.query.filter_by(
                    name=entry.name).update(dict(tag=entry.displayTag()))
                print('TagNameMapping - rc:', rows_changed)

            print('commit mapping')
            db.session.commit()

            return redirect(url_for('index'))

        # The user pressed the "Cancel" button
        else:
            return redirect(url_for('index'))
    '''
    # put down here or causes validate not to work
    print('entries id:',entry.category_id)
    subCat = Category.query.filter_by(id=entry.category_id).first()
    parCat = 0
    if subCat and (subCat.parent_id != 0):
        parCat = Category.query.filter_by(id=subCat.parent_id).first().id
    print('set drop down to:', parCat)
    form.category.default = parCat #7 # using number works with process()
    form.process()

    # https://youtu.be/I2dJuNwlIH0?t=69
    # https: // github.com / PrettyPrinted / dynamic_select_flask_wtf_javascript
    # form.subCategory.choices = [(subCat.id,subCat.name) for subCat in .....some DB query]
    '''
    return render_template('category.html', form=form, entry=entry)