コード例 #1
0
    def insert():
        """New Category"""
        form = CategoryForm(obj=request.json)

        if form.validate():
            name = form.name.data
            is_active = form.is_active.data

            category = Category(name=name, is_active=is_active)

            db.session.add(category)

            try:
                db.session.commit()

            except:
                db.session.rollback()
                # return error message
                return {"error": "Error when adding an category"}

            # success, return new item
            return {"item": category.serialize()}

        # return form errors
        return {"errors": form.errors}
コード例 #2
0
ファイル: views.py プロジェクト: tdhunt631/cs4990
def addCat(request):
    if request.method == 'POST':
        form = CategoryForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            newCat = Category()
            newCat.name = cd.get('name')
            newCat.description = cd.get('description')
            newCat.save()
            if request.is_ajax():
                categories = Category.objects.all()
                context = {
                    'categories': categories,
                }
                return render_to_response(
                    'inventory/getCats.html',
                    context,
                    context_instance=RequestContext(request))
            else:
                return HttpResponseRedirect('/inventory/')

    message = "Oops, it broke! You should enter in something valid."
    form = CategoryForm()
    categories = Category.objects.all()
    context = {
        'message': message,
        'form': form,
        'categories': categories,
    }
    return render_to_response('inventory/index.html',
                              context,
                              context_instance=RequestContext(request))
コード例 #3
0
ファイル: views.py プロジェクト: chengzhao41/Rango
def add_category(request):
    # Get the context from the request.
    context = RequestContext(request)

    # A HTTP POST?
    if request.method == 'POST':
        form = CategoryForm(request.POST)

        # Have we been provided with a valid form?
        if form.is_valid():
            # Save the new category to the database.
            category = form.save(commit=True)

            # Now call the index() view.
            # The user will be shown the homepage.

            action.send(request.user, verb='added', action_object=category)
            return index(request)
        else:
            # The supplied form contained errors - just print them to the terminal.
            print form.errors
    else:
        # If the request was not a POST, display the form to enter details.
        form = CategoryForm()

    # Bad form (or form details), no form supplied...
    # Render the form with error messages (if any).
    return render_to_response('rango/add_category.html', {'form': form}, context)
コード例 #4
0
ファイル: views.py プロジェクト: vanadium23/catalog-project
def category_update(category_name):
    """Update category name and description in database"""
    if 'username' not in login_session:
        return redirect(url_for('login'))
    category = Category.query.filter(Category.name == category_name).first()
    if category.author_id != login_session['user_id']:
        return ""
    form = CategoryForm()
    if form.validate_on_submit():
        try:
            category.name = form.name.data
            category.description = form.description.data
            db_session.add(category)
            db_session.commit()
            return redirect(url_for('category_view',
                                    category_name=form.name.data))
        except IntegrityError:
            db_session.rollback()
            flash("Category name must be unique value")
        except Exception:
            db_session.rollback()
            flash("Database error encountered")
    flash_errors(form)
    return redirect(url_for('category_edit',
                            category_name=category_name))
コード例 #5
0
def editCategory(name):
    """Edit a named category or render a form.

    Args: A category name

    Returns: Edited category or render a form.
    """
    # Store caetgory and logged in user
    category = Category.query.filter_by(name=name).first_or_404()
    user = Users.query.filter_by(id=login_session['users_id']).first_or_404()
    # Verify that the logged in user is creator or admin
    if category.users_id != login_session['users_id'] and not user.admin:
        flash(' You are not authorized to make that edit.')
        return redirect(
            url_for('category.showCategory', category_id=category_id))
    # Initiate the form.
    form = CategoryForm(obj=category)
    # On POST of a valid form, edit the category.
    if form.validate_on_submit():
        category.name = form.name.data
        category.description = form.description.data
        category.picture = form.picture.data
        db.session.add(category)
        db.session.commit()
        flash(' Category %s Successfully Edited' % category.name)
        return redirect(url_for('category.showCategory', name=category.name))
    else:
        return render_template('editCategory.html',
                               form=form,
                               category=category)
コード例 #6
0
def editcategory(id):
    """
    this allow users to edit categories
    """
    category = Category.query.get_or_404(id)
    form = CategoryForm(request.form)
    user_id = login_session['gplus_id']
    owner_id = category.user_id
    if request.method == 'POST' and form.validate():
        # editing done here
        category.name = request.form['name']
        if user_id == owner_id:
            db.session.commit()
            flash('Category successfully updated', 'success')
        return redirect('/')
    else:
        user_id = login_session['gplus_id']
        owner_id = category.user_id
        if user_id == owner_id:
            form.name.data = category.name
            return render_template('editcategory.html',
                                   form=form,
                                   category=category)
        else:
            flash('Sorry you are not a owner of this category', 'danger')
            return redirect('/')
コード例 #7
0
ファイル: views.py プロジェクト: cnwalker/eventbrite
def index(request):
    args = {}
    if request.method == 'POST':
        form = CategoryForm(request.POST)
        if form.is_valid():
            # Passes error through if user selected more than three category ids
            category_num = len(form.cleaned_data['category_ids'])
            if category_num > 3:
                return HttpResponseRedirect('/?too_many_categories=true')
            if category_num == 0:
                return HttpResponseRedirect('/?too_few_categories=true')
            event_search_url = "?category_ids=" + ",".join(form.cleaned_data['category_ids'])
            event_search_url += "&location=" + form.cleaned_data['location']
            return HttpResponseRedirect('/events/' + event_search_url)
        else:
            return HttpResponseRedirect('/?no_location=true')
    else:
        # Raises an error if user has not selected any categories
        if request.GET.get('too_few_categories'):
            args['error'] = "You must select at least 1 category"

        # Raises an error if user selected more than three category ids
        if request.GET.get('too_many_categories'):
            args['error'] = "You may select no more than 3 categories"

        if request.GET.get('no_location'):
            args['error'] = "You must include a location"
        # Form will initialize with valid categories from eventbrite API
        args['category_form'] = CategoryForm()
        return render(request, 'index.html', args)
コード例 #8
0
ファイル: app.py プロジェクト: dai175/foster
    def create_category_submission(jwt):
        form = CategoryForm()
        if not form.validate_on_submit():
            return jsonify({'success': False})

        category = Category(name=request.form.get('name'),
                            description=request.form.get('description'))

        error = False

        try:
            db.session.add(category)
            db.session.commit()

            # Save images as
            file = request.files['image']
            if file:
                filename = upload_image(file, consts.LEAD_CATEGORY,
                                        category.id)
                category.image = filename
                db.session.commit()
        except exc.SQLAlchemyError:
            error = True
            db.session.rollback()
        finally:
            db.session.close()

        if not error:
            flash('Category {} was successfully listed!'.format(
                request.form['name']))
        else:
            flash('An error occurred. Category {} could not be listed.'.format(
                request.form['name']))

        return jsonify({'success': not error})
コード例 #9
0
ファイル: views.py プロジェクト: Tibodef/PythonBlog
    def put(self, id):
        category = Category.get_by_id(id)
        if category is None:
            flash(gettext('The category was not found'), 'error')
            return redirect(url_for('CategoriesView:index'))
        if not category.can_edit():
            abort(401)

        if request.method in ['POST', 'PUT']:
            form = CategoryForm()
            if form.validate_on_submit():
                try:
                    form.populate_obj(category)
                    category.save()
                    flash(gettext('Category was succesfully saved'))
                    return util.redirect_json_or_html(url_for('CategoriesView:index'), 'category')
                except:
                    return util.redirect_json_or_html(url_for('CategoriesView:index'), 'category', gettext('Error while updating the category'))
            else:
                if request.is_xhr:
                    return util.redirect_json_or_html(url_for('CategoriesView:index'), 'category', gettext('Invalid submission, please check the message below'))
                else:
                    flash(gettext('Invalid submission, please check the message below'), 'error')
        else:
            form = NewCategoryForm(category)
        return render_template('admin/categories/edit.html',
            title=gettext('Edit Category: %(name)s', name=category.name),
            form=form,
            category=category)
コード例 #10
0
ファイル: views.py プロジェクト: luog1992/django-blog
def cat_modify_post(request, id='0', cxt={}):
    assert request.method == 'POST'
    cxt.update(csrf(request))
    category = Category.objects.get(id=int(id))
    initial = {
        'name': category.name,
        'color': category.color,
        'public': category.public
    }
    category_form = CategoryForm(request.POST, initial=initial)
    cxt.update({'category_form': category_form, 'category': category})
    if category_form.is_valid():
        data = category_form.cleaned_data
        category_name = data['name']
        if 'name' in category_form.changed_data:
            if Category.objects.filter(name=category_name):
                category_form.add_error('name', 'Duplicated Category Name')
            else:
                Category.objects.filter(id=int(id)).update(
                    name=data['name'],
                    color='#' + data['color'][-6:],
                    public=data['public']
                )
        else:
            Category.objects.filter(id=int(id)).update(
                color='#' + data['color'][-6:],
                public=data['public']
            )
    return render_to_response('category_modify.html', cxt)
コード例 #11
0
ファイル: index.py プロジェクト: jctt1983/PythonBlog
    def post(self):
        form = CategoryForm()

        if form.is_submitted():
            try:
                if not form.validate():
                    raise Exception(_('ERROR_INVALID_SUBMISSION'))

                category = Category.create()

                if not form.slug.data:
                    form.slug.data = form.name.data

                form.slug.data = Category.urlify(form.slug.data)

                form.populate_obj(category)
                category.save()

                return render_view(url_for('CategoriesView:put', id=category.id),
                                   message=_('CATEGORY_CREATE_SUCESS'),
                                   redirect=True)
            except Exception as e:
                flash(e.message, 'error')

        return render_view('admin/categories/add.html', form=form)
コード例 #12
0
ファイル: views.py プロジェクト: qgreg/itemcatalog
def editCategory(name):
    """Edit a named category or render a form.

    Args: A category name

    Returns: Edited category or render a form.
    """
    # Store caetgory and logged in user
    category = Category.query.filter_by(name=name).first_or_404()
    user = Users.query.filter_by(id=login_session["users_id"]).first_or_404()
    # Verify that the logged in user is creator or admin
    if category.users_id != login_session["users_id"] and not user.admin:
        flash(" You are not authorized to make that edit.")
        return redirect(url_for("category.showCategory", category_id=category_id))
    # Initiate the form.
    form = CategoryForm(obj=category)
    # On POST of a valid form, edit the category.
    if form.validate_on_submit():
        category.name = form.name.data
        category.description = form.description.data
        category.picture = form.picture.data
        db.session.add(category)
        db.session.commit()
        flash(" Category %s Successfully Edited" % category.name)
        return redirect(url_for("category.showCategory", name=category.name))
    else:
        return render_template("editCategory.html", form=form, category=category)
コード例 #13
0
def category_edit(type=0, id=None, name=None):
    # 商品/服务分类修改
    form = CategoryForm()
    form.submit.label.text = u'修改'
    category = Category.query.filter_by(id=id).first_or_404()
    is_flag = True
    if request.method == 'GET':
        form.name.data = category.name
        form.remarks.data = category.remarks
    if form.validate_on_submit():
        if category.name != form.name.data and Item.query.filter_by(
                cate=name).first():
            is_flag = False
            flash(u'您选择的分类已被商品/服务项目使用,不能修改名称', 'err')
        if category.name != form.name.data and Category.query.filter_by(
                name=form.name.data).first():
            is_flag = False
            flash(u'您输入的分类已存在,名称不能重复', 'err')
        if is_flag == False:
            return render_template('admin/category_edit.html',
                                   form=form,
                                   type=type)
        category.name = form.name.data
        category.remarks = form.remarks.data
        db.session.add(category)
        oplog = Oplog(user_id=session['user_id'],
                      ip=request.remote_addr,
                      reason=u'修改商品/服务项目分类:%s' % form.name.data)
        db.session.add(oplog)
        db.session.commit()
        flash(u'分类修改成功', 'ok')
        return redirect(url_for('admin.category_list', type=type))
    return render_template('admin/category_edit.html', form=form, type=type)
コード例 #14
0
def index(request):
    """
    This defines the index page. It holds form available at the page. 
    """

    # Writing action of form when categories are submitted
    if request.method == 'POST':
        form = CategoryForm(request.POST)

        if form.is_valid():

            # Fetching the three categories listed by user
            category1 = form.cleaned_data['field0']
            category2 = form.cleaned_data['field1']
            category3 = form.cleaned_data['field2']
            page = 1  #Setting initial search page to 1

            redirect_url = 'listings/' + category1 + '/' + category2 + '/' + category3 + '/' + str(
                page)

            return HttpResponseRedirect(redirect_url)

    # Action of form otherwise
    else:
        form = CategoryForm()

    return render(request, 'index.html', {'form': form})
コード例 #15
0
ファイル: views.py プロジェクト: catjake/rango
def add_category(request):
    """
    Either show a form or create a new instance of one.
    """

    # Is request HTTP POST or GET?
    if request.method == "POST":
        form = CategoryForm(request.POST)
        if form.is_valid():
            category = form.save(commit=False)
            setattr(category,"url", Category._encode_url_name(category.name))
            category.save()

            # now call the index() view
            # user redirected to home page
            return index(request)
        else:
            # Uh oh, supplied form contains error - print out to console
            print form.errors
    else:
        # request not a POST, display the form to enter details
        form = CategoryForm()

    # Bad form (or form details), no form supplied...
    # Render the form with error messages (if any).
    return _process_request(request, {"form": form}, "rango/add_category.html")
コード例 #16
0
ファイル: categories.py プロジェクト: richardhenyash/freefrom
def category_edit():
    """
    Route for category edit
    """
    # request Form data
    form = CategoryForm(request.form)
    # Get categories collection from database
    categories = mongo.db.categories.find().sort("name", 1)
    existing_category_name = None
    if request.method == "POST":
        existing_category_name = category_get_selection("Update")
    if request.method == "POST" and form.validate():
        category_name = form.name.data.lower()
        if existing_category_name and category_check(category_name):
            category_id = category_get_id(existing_category_name)
            # Update category in the database
            if category_id:
                category_update(category_id, category_name)
                return redirect(url_for('products.search'))
            else:
                return redirect(url_for('categories.category_edit'))
        else:
            return render_template(
                "category_edit.html",
                categories=categories,
                existing_category_name=existing_category_name,
                form=form)

    return render_template("category_edit.html",
                           categories=categories,
                           existing_category_name=existing_category_name,
                           form=form)
コード例 #17
0
def register():
    form = CategoryForm(request.form)
    if request.method == 'POST' and form.validate():
        # auto generate category id in betwen 10 - 20000
        category = Category(randint(10, 20000), form.name.data)
        db_session.add(category)
        return redirect('/home')
    return render_template('category_create.html', form=form)
コード例 #18
0
ファイル: views.py プロジェクト: iredkoz/testapp
def editCategory(cat_id):
    catForm = CategoryForm()
    cat = Category.query.get(cat_id)
    if catForm.validate_on_submit():
        cat.name = catForm.name.data
        cat.note=catForm.note.data
        db.session.commit()
    return redirect(url_for('shopapp.shop_main'))
コード例 #19
0
ファイル: views.py プロジェクト: SuZhiBai/flaskblog
def addcategory():
    form = CategoryForm()
    if form.validate_on_submit():
        category = Category(name=form.name.data,)
        db.session.add(category)
        db.session.commit()
        return redirect(url_for('admin.listcategory'))
    return render_template('/addcategory.html', form=form)
コード例 #20
0
def editCategory(cat_id):
    catForm = CategoryForm()
    cat = Category.query.get(cat_id)
    if catForm.validate_on_submit():
        cat.name = catForm.name.data
        cat.note = catForm.note.data
        db.session.commit()
    return redirect(url_for('shopapp.shop_main'))
コード例 #21
0
def selectcategory():

    mytoken = session.get('mytoken')
    payload = {}
    headers = {
        'Account': 'stesa',
        'Token': mytoken,
    }
    projectid = session.get('project')

    caturl = 'https://api.inventsys.com.br/v4/projects/' + projectid + '/categories'
    categorias = requests.request('GET',
                                  caturl,
                                  headers=headers,
                                  data=payload,
                                  allow_redirects=False)

    catvariavel = ""
    variavelnome = ""
    catlista = []
    listanomes = []
    for i in range(0, len(categorias.json()['categories'])):
        cat = (categorias.json()['categories'][i]['id'])
        nome = (categorias.json()['categories'][i]['name'])
        catvariavel = (str(cat))
        catlista.append(catvariavel)
        variavelnome = (str(nome))
        listanomes.append(variavelnome)
    tulpa = [(x, y) for x, y in zip(catlista, listanomes)]

    form = CategoryForm()
    form.selecionacategoria.choices = tulpa

    if form.validate_on_submit():
        if categorias:
            session['category'] = str(form.selecionacategoria.data)
            session['categoryname'] = str(
                dict(form.selecionacategoria.choices).get(
                    form.selecionacategoria.data))
            session['inicio'] = form.inicio.data
            session['fim'] = form.fim.data
            flash(
                f'Categoria ' + session['categoryname'] +
                ' selecionado com sucesso!', 'success')
            return redirect(
                url_for('loginpostgis',
                        mytoken=session['mytoken'],
                        project=session['project'],
                        category=session['category']))
        else:
            flash('Categoria não pode ser selecionada. Tente novamente.',
                  'danger')

    return render_template('selectcategory.html',
                           title='SelectCategory',
                           mytoken=mytoken,
                           form=form)
コード例 #22
0
ファイル: admin.py プロジェクト: wangch230/myblog
def new_category():
    form = CategoryForm()
    if form.validate_on_submit():
        name = form.name.data
        category = Category(name=name)
        db.session.add(category)
        db.session.commit()
        flash('Category created.', 'success')
        return redirect(url_for('.manage_category'))
    return render_template('admin/new_category.html', form=form)
コード例 #23
0
ファイル: views.py プロジェクト: SuZhiBai/flaskblog
def editcategory():
    form = CategoryForm()
    form.name.data = request.args.get('category_id')
    if form.validate_on_submit():
        category = Category.query.filter_by(name=form.name.data).first()
        category.name = form.name.data
        db.session.add(category)
        db.session.commit()
        return redirect(url_for('admin.listcategory'))
    return render_template('/addcategory.html', form=form)
コード例 #24
0
ファイル: webserver.py プロジェクト: filipecalasans/budgetfy
def category():
    form = CategoryForm()

    if form.validate_on_submit():
        services.add_category(name=form.name.data,
                              description=form.description.data,
                              user=current_user)
        return redirect(url_for('user_expenses'))

    return render_template('category.html', form=form)
コード例 #25
0
ファイル: views.py プロジェクト: mew93/movies-db
def addCategory(request):
    if request.method == "POST":
        form = CategoryForm(request.POST)
        if form.is_valid():
            new_category = Category.objects.create(**form.cleaned_data)
            return HttpResponseRedirect(reverse('tommymovies:history'))
    else:
        form = CategoryForm()

    return render(request, 'tommymovies/addCategory.html', {'form': form})
コード例 #26
0
ファイル: views.py プロジェクト: VBelozyorov/libcms
def category_edit(request, id):

    category = get_object_or_404(Category, id=id)
    category_titles = CategoryTitle.objects.filter(category=category)

    category_titles_langs = {}
    for lang in settings.LANGUAGES:
        category_titles_langs[lang] = None


    for category_title in category_titles:
        category_titles_langs[category_title.lang] = category_title

    if request.method == 'POST':
        category_form = CategoryForm(request.POST,prefix='category_form', instance=category)

        category_title_forms = []
        for lang in settings.LANGUAGES:
            category_title_forms.append({
                'form':CategoryTitleForm(request.POST,prefix='category_title_' + lang[0]),
                'lang':lang[0]
            })

        if category_form.is_valid():

            category = category_form.save(commit=False)
            category.parent = parent
            category.save()

            valid = False
            for category_title_form in category_title_forms:
                valid = category_title_form['form'].is_valid()
                if not valid:
                    break
                #            print 'valid', valid
            if valid:
                for category_title_form in category_title_forms:
                    category_title = category_title_form['form'].save(commit=False)
                    category_title.lang = category_title_form['lang']
                    category_title.category = category
                    category_title.save()
                return redirect('ask_librarian:administration:categories_list')
    else:
        category_form = CategoryForm(prefix="category_form")
        category_title_forms = []
        for lang in settings.LANGUAGES:
            category_title_forms.append({
                'form':CategoryTitleForm(prefix='category_title_' + lang[0]),
                'lang':lang[0]
            })

    return render(request, 'ask_librarian/administration/create_category.html', {
        'category_form': category_form,
        'category_title_forms': category_title_forms,
        })
コード例 #27
0
ファイル: views.py プロジェクト: berkantaydin/trainingProject
def categoryAdd(request):
    if request.method == "POST":
        cf = CategoryForm(request.POST, prefix="category")
        if cf.is_valid():
            cf.save()
            messages.success(request,
                             _('Category Added.'))
            return HttpResponseRedirect(reverse("pageCategoryAdd"))
    else:
        cf = CategoryForm(prefix="category")
    return render(request, 'categoryadd.html', dict(categoryForm=cf))
コード例 #28
0
ファイル: views.py プロジェクト: zishanAhmad/rango
def add_category(request):
    if request.method == 'POST':
        form = CategoryForm(request.POST)
        if form.is_valid():
            form.save(commit=True)
            return index(request)
        else:
            print form.errors
    else:
        form = CategoryForm()
    return render(request, 'rango/add_category.html', {'form': form})
コード例 #29
0
def admin_category():

    form = CategoryForm()
    if request.method == 'POST' and form.validate_on_submit():
        cat_name = form.cat_name.data.strip()
        cat_description = form.cat_description.data.strip()
        Category.save(cat_name, cat_description)
        categories = Category.query.all()
        return render_template('admin_categories.html', title='Admin', user=current_user, categories=categories)

    return render_template('admin_new_category.html', title='Admin', form=form, user=current_user)
コード例 #30
0
ファイル: views.py プロジェクト: iredkoz/testapp
def newCat():
    catForm = CategoryForm()
    name = catForm.name.data
    if catForm.validate_on_submit():
        if Category.query.filter_by(name=name).first():
            flash('Category already exists!','alert-danger')
        else:
            cat = Category(name=name, note = catForm.note.data)
            db.session.add(cat)
            db.session.commit()
    return redirect(url_for('shopapp.shop_main'))
コード例 #31
0
def newCat():
    catForm = CategoryForm()
    name = catForm.name.data
    if catForm.validate_on_submit():
        if Category.query.filter_by(name=name).first():
            flash('Category already exists!', 'alert-danger')
        else:
            cat = Category(name=name, note=catForm.note.data)
            db.session.add(cat)
            db.session.commit()
    return redirect(url_for('shopapp.shop_main'))
コード例 #32
0
ファイル: views.py プロジェクト: reaandrew/GAE-Examples
def create_category_submit(request):
    category = Category(user=request._user, name="DEFAULT")
    data = CategoryForm(data=request.POST, instance=category)

    if data.is_valid():
        entity = data.save(commit=False)
        entity.put()
        return HttpResponseRedirect("/")

    return render_to_response('home/create_category.html',
                              {'category_form': data})
コード例 #33
0
ファイル: euroInAFlask.py プロジェクト: vikin91/euroInAFlask
def categoryEdit(id):
    category = SpendingCategory.query.filter(SpendingCategory.id == id).one()

    form = CategoryForm(request.form, obj=category)
    if request.method == 'POST':
        form.populate_obj(category)
        db.session.merge(category)
        db.session.commit()

        flash('Category '+category.name+' updated.')

    return render_template('edit_category.html', f=form, obj=category)
コード例 #34
0
ファイル: views.py プロジェクト: cenzino/vp-gae
def new_category():
    form = CategoryForm()
    if form.validate_on_submit():
        category = Category(name=form.name.data)
        try:
            category.put()
            flash(u"Example %s successfully saved." % category.name, "success")
            return redirect(url_for("list_categories"))
        except CapabilityDisabledError:
            flash(u"App Engine Datastore is currently in read-only mode.", "info")
            return redirect(url_for("list_categories"))
    return render_template("new_category.html", form=form)
コード例 #35
0
def add_category(request):
    if request.method == "POST":
        form = CategoryForm(request.POST)
        if form.is_valid():
            form.save()
            return index(request)
        else:
            print form.errors

    else:
        form = CategoryForm()
    return render(request, "rango/add_category.html", {"form": form})
コード例 #36
0
def add_category(request):

    if request.is_ajax():
        name = request.POST['name'].strip()
        description = request.POST['description']
        shared = request.POST['shared']

        if shared == "false":
            shared = False
        else:
            shared = True

        category = Category(user=request.user,
                            name=name,
                            description=description,
                            shared=shared)

        # Saves it
        category.save()

        id = category.id

        category_url = Category.objects.get(id=id).slug

        return JsonResponse({
            "response": "Success",
            "category": category_url,
            "category_id": id
        })

    if request.method == "POST":
        category_data = request.POST
        category_data['name'] = category_data['name'].strip()
        if category_data['name'] == "":
            return render(request, "fhs/add_category.html", {"invalid": True})

        category_form = CategoryForm(data=category_data)
        if category_form.is_valid():
            try:
                category = category_form.save(commit=False)
                category.user = request.user
                category.save()

                return HttpResponseRedirect('/fhs/profile/' +
                                            request.user.username)
            except:
                return render(request, "fhs/add_category.html",
                              {"existent": True})
        else:
            return render(request, "fhs/add_category.html", {"existent": True})

    return render(request, "fhs/add_category.html", {})
コード例 #37
0
ファイル: views.py プロジェクト: becomingGuru/baba
def frontend(request):
	uform = UserForm(request.POST or None)
	cform = CategoryForm(data=request.POST or None)
	
	if request.method=='POST' and uform.is_valid() and cform.is_valid():
		user_obj = uform.save(commit=False)
		user_obj.save()
		cform.save(user_obj)
		messages.success(request, 'You are signed-up for the selected notifications')
		return redirect(user_obj.get_edit_url())
	return render_to_response('notification.html',
	                          locals(),
	                          RequestContext(request))
コード例 #38
0
def newCategory(user):
    error = None
    form = CategoryForm()
    if request.method == 'POST':
        if form.validate_on_submit():
            category = Category(name=form.name.data)
            db.session.add(category)
            db.session.commit()
            redirect(url_for('index'))
        else:
            error = 'All fields are required'
    params = dict(user=user, form=form, error=error)
    return render_template('newCategory.html', **params)
コード例 #39
0
ファイル: views.py プロジェクト: REAANDREW/GAE-Examples
def create_category_submit(request):
	category = Category(user=request._user, name="DEFAULT")
	data = CategoryForm(data=request.POST, instance=category)
	
	if data.is_valid():
		entity = data.save(commit=False)
		entity.put()
		return HttpResponseRedirect("/")

	return render_to_response('home/create_category.html',
	{
		'category_form' : data 
	})
コード例 #40
0
ファイル: views.py プロジェクト: mihneadb/notice
def category_add(request):
    if request.method == 'GET':
        form = CategoryForm()
    else:
        form = CategoryForm(request.POST)
        if form.is_valid():
            category = form.save()
            return redirect('homepage')

    data = {
        'form':form,
    }
    return render_to_response('category_add.html', data, context_instance=RequestContext(request))
コード例 #41
0
ファイル: views.py プロジェクト: junclemente/catalog-postgres
def add_category():
    form = CategoryForm()
    categories = session.query(Category).all()
    if form.validate_on_submit():
        name = form.name.data
        new_category = Category(name=name, user_id=login_session['user_id'])
        session.add(new_category)
        session.commit()
        flash('New Category Added', "flash-success")
        return redirect(url_for('category_list', cat_id=new_category.id))
    return render_template('add_category.html',
                           categories=categories,
                           form=form)
コード例 #42
0
ファイル: admin.py プロジェクト: wangch230/myblog
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('blog.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)
コード例 #43
0
ファイル: views.py プロジェクト: cenzino/vp-gae
def edit_category(category_name):
    category = Category.get_by_key_name(category_name)
    form = CategoryForm(obj=category)

    if form.validate_on_submit():
        form.populate_obj(category)
        try:
            category.put()
            flash(u"Example %s successfully saved." % category.name, "success")
            return redirect(url_for("list_categories"))
        except CapabilityDisabledError:
            flash(u"App Engine Datastore is currently in read-only mode.", "info")
            return redirect(url_for("list_categories"))
    return render_template("edit_category.html", form=form, category_name=category.id)
コード例 #44
0
def admin_edit_category(cat_id):

    form = CategoryForm()
    if request.method == 'POST' and form.validate_on_submit():
        cat_name = form.cat_name.data.strip()
        cat_description = form.cat_description.data.strip()
        Category.update(cat_id, cat_name, cat_description)
        categories = Category.query.all()
        return render_template('admin_categories.html', title='Admin', user=current_user, categories=categories)
    else:
        category = Category.query.filter_by(cat_id=cat_id).first()
        form.cat_name.data = category.cat_name
        form.cat_description.data = category.cat_description
        return render_template('admin_edit_category.html', title='Admin', form=form, user=current_user)
コード例 #45
0
ファイル: views.py プロジェクト: mihneadb/notice
def category_edit(request, id):
    category = get_object_or_404(Category, id=id)
    if request.method == 'GET':
        form = CategoryForm(instance=category)
    else:
        form = CategoryForm(request.POST, instance=category)
        if form.is_valid():
            form.save()
            return redirect('category_list', id=id)

    data = {
        'form': form,
        'category': category,
    }
    return render_to_response('category_edit.html', data, context_instance=RequestContext(request))
コード例 #46
0
ファイル: views.py プロジェクト: mshameers/theory_website
def category():
	form = CategoryForm(formdata=request.form or None)
	if request.method == 'POST':
		if request.form and form.validate():
			c = Category(name=form.name.data, shortName=form.shortName.data)
			db.session.add(c)
			db.session.commit()
			return redirect(url_for('category'))
		else:
		    flash('There was an error with your input: %s' % form.errors)
		    return redirect(url_for('category'))
		
	else:
		categories = Category.query.all()
		return render_template('category.html', categories=categories, form=form)
コード例 #47
0
ファイル: views.py プロジェクト: timkaboya/tango_with_django
def add_category(request):
    context = RequestContext(request)
    cat_list = get_category_list()
    if request.method == 'POST':
        form = CategoryForm(request.POST)

        if form.is_valid():
            form.save(commit=True)
            return index(request)
        else:
            print form.errors
    else:
        form = CategoryForm()

    return render_to_response('rango/add_category.html', {'form': form, 'cat_list':cat_list}, context)
コード例 #48
0
ファイル: views.py プロジェクト: jbrasher0623/lib
def create(request):
    if request.POST:
        form = CategoryForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/categories/all')
    else:
        form = CategoryForm()

    args = {}
    args.update(csrf(request))

    args['form'] = form

    return render_to_response('create_category.html', args)
コード例 #49
0
ファイル: views.py プロジェクト: lig/picket_classic
def category(request, categoryId):
    
    category = get_object_or_404(Category, pk=categoryId)
    
    if request.method == 'POST':
        categoryForm = CategoryForm(request.POST, instance=category)
        if categoryForm.is_valid():
            category = categoryForm.save()
            request.user.message_set.create(message=_('Category updated'))
            return redirect(category.project.get_absolute_url())
    else:
        categoryForm = CategoryForm(instance=category)
    
    return direct_to_template(request, 'picket/admin/category_manage.html',
        {'category': category, 'category_form': categoryForm,})
コード例 #50
0
def newCategory():
    form = CategoryForm()
    if form.validate_on_submit():
        newCategory = Category(
            name=request.form['name'],
            description=request.form['description'],
            user_id=login_session['user_id'])
        session.add(newCategory)
        session.commit()
        flash("New category created.")
        return redirect(url_for('showCatalog'))
    else:
        if request.method == 'POST':
            flash("Error while creating the category. \
                Please fill all the required fields")
        return render_template('newcategory.html', form=form)
コード例 #51
0
def add_category():

    form = CategoryForm(request.form)
    if request.method == 'POST':
        if form.validate():
            if __get_category_by_name(form.name.data) != None:
                return render_template('views/category_form.html', page_name='edit_category', page_title='Edit Category', error='A category with that name already exists.')

            category = Category(name=form.name.data)
            category.save()

            return list_categories(success='Created new category "{}".'.format(form.name.data))
        else:
            return render_template('views/category_form.html', page_name='add_category', page_title='Add Category', errors=parse_form_errors(form.errors.items()))

    return render_template('views/category_form.html', page_name='add_category', page_title='Add Category')
コード例 #52
0
def addcategory():
    """
    this allow users to add categories
    """
    form = CategoryForm(request.form)
    if request.method == 'POST' and form.validate():
        # saving done here
        category = Category(name=request.form['name'],
                            user_id=login_session['gplus_id'])

        db.session.add(category)
        db.session.commit()
        flash('Category successfully added', 'success')
        return redirect('/')
    else:
        return render_template('addcategory.html', form=form)
コード例 #53
0
def shop_main():
    listForm = ListForm()
    itemForm = ItemForm()
    catForm = CategoryForm()
    prodForm = ProductForm()
    shopForm = ShopForm()

    lists = Slist.query.all()
    cats = Category.query.all()
    shops = Shop.query.all()
    prods = db.session.query(Slist.name,
                             func.count(Item.id)).join(Item).group_by(Slist.id)
    prods = dict(prods)

    return render_template('shopapp/shopapp.html',
                           units=units,
                           lists=lists,
                           listForm=listForm,
                           itemForm=itemForm,
                           catForm=catForm,
                           prodForm=prodForm,
                           shopForm=shopForm,
                           cats=cats,
                           shops=shops,
                           prods=prods)
コード例 #54
0
ファイル: admin_panel.py プロジェクト: zpidreamteam/ZPI
def add_category():
    form = CategoryForm()

    if form.validate_on_submit():
        category = Category(name = form.name.data)

        db.session.add(category)
        db.session.commit()

        flash("Poprawnie dodano kategorie")

        return redirect('admin/categories')

    return render_template('admin/add_category.html',
                            title='Nowa kategoria',
                            form=form)
コード例 #55
0
def delete_category(request):
    form = CategoryForm(request.POST)
    if form.is_valid():
        categoryId = form.cleaned_data.get('category_id')
        categoryModel = CategoryModel.objects.all().filter(
            pk=categoryId).first()
        if categoryModel:
            articalCount = categoryModel.articalmodel_set.all().count()
            if articalCount > 0:
                return xtjson.json_params_error(message='无法删除,该分类下还有文章')
            else:
                categoryModel.delete()
                return xtjson.json_result()

    else:
        return form.get_error_response()
コード例 #56
0
def editCategory(category_id):
    '''
    Edit a category, requires to be logged and checks if the user is the
    category owner in the html rendered file.
    category_id is the id of the category to be edited.
    Returns a redirect to show categories after edition in case of POST or the
    edit category html page in case of GET.
    '''
    cat = Category.query.filter_by(id=category_id).first()
    form = CategoryForm(request.form)
    if request.method == 'POST' and form.validate():
        cat.name = request.form['name']
        db.session.commit()
        flash("Category updated")
        return redirect(url_for('showCategories'))
    else:
        return render_template('edit_category.html', cat=cat, form=form)
コード例 #57
0
def newCategory():
    '''
    Add a category, requires to be logged and makes the user the category
    owner.
    Returns a redirect to show categories after adding the category in case of
    POST or the add category html page in case of GET.
    '''
    form = CategoryForm(request.form)
    if request.method == 'POST' and form.validate():
        newCategory = Category(name=form.name.data,
                               username=session['username'])
        db.session.add(newCategory)
        db.session.commit()
        flash("New category created")
        return redirect(url_for('showCategories'))
    else:
        return render_template('new_category.html', form=form)
コード例 #58
0
def addMovie(request):
    movie_form = MovieForm()
    movie_form.fields.pop('categories')
    category_form = CategoryForm()
    return render(request, 'tommymovies/addMovie.html', {
        'movie_form': movie_form,
        'category_form': category_form
    })
コード例 #59
0
def add_category():
    user = g.user
    form = CategoryForm()
    if form.validate_on_submit():
        try:
            category = db.session.query(Category).filter_by(
                category_text=form.category.data.strip().lower()).one()
        except:
            category = Category(
                category_text=form.category.data.strip().lower())
            db.session.add(category)
            db.session.commit()
            flash(
                "The Category: '{}' was added".format(
                    form.category.data.strip()), 'success')
            return redirect(url_for('dashboard'))
    return render_template('add_category.html', user=user, form=form)