Esempio n. 1
0
def new_products_item():
    form = ProductForm()
    if form.validate_on_submit():
        db_sess = db_session.create_session()
        filename = secure_filename(form.image.data.filename)
        form.image.data.save('uploads/'+filename)
        product = Product(form.title.data, form.content.data,
                          '/img/'+filename, form.price.data,
                          form.is_featured.data)
        db_sess.add(product)
        db_sess.commit()
        return redirect(f"/admin/products")
    return render_template('admin/products_item.html', title='Новый Товар', form=form)
Esempio n. 2
0
def add_product():
    form = ProductForm()
    db_sess = db_session.create_session()
    categories = db_sess.query(Category)
    category_flag = 'None'
    if form.validate_on_submit():
        product = Product(title=form.title.data,
                          description=form.description.data,
                          producer=form.producer.data,
                          price=float(form.price.data),
                          count=int(form.count.data),
                          advantage=form.advantage.data)
        if form.picture.data:
            f = form.picture.data
            parent_dir = path.dirname(path.abspath(__file__))
            basename = parent_dir + '\\static\\pictures\\pic'
            suffix = datetime.now().strftime("%y%m%d_%H%M%S")
            filename = "_".join([basename, suffix, '.png'])
            g = open(filename, 'wb')
            g.write(f.getbuffer())
            g.close()
            product.picture = '/static/pictures/pic_' + suffix + '_.png'

        cat = db_sess.query(Category).filter(
            Category.title == form.category.data).first()
        if not cat:
            cat = db_sess.query(Category).filter(
                Category.id == form.category.data).first()
        product.category = cat.id

        db_sess.add(product)
        db_sess.commit()
        return redirect('/')
    return render_template('product.html',
                           title='Добавление товара',
                           form=form,
                           categories=categories,
                           category=category_flag)
Esempio n. 3
0
def product_add():
    form = ProductForm()
    if form.is_submitted():
        db_sess = db_session.create_session()
        count = len(db_sess.query(Product).all())
        product = Product()
        product.title = form.title.data.lower()
        product.content = form.content.data
        product.connection = form.connection.data
        if not form.connection.data.isdigit() and str(
                form.connection.data) != 11 and not str(
                    form.connection.data).startswith('8'):
            return render_template('product.html',
                                   title='Добавление товара',
                                   form=form,
                                   message='Неверный формат ввода телефона')
        product.category = request.form['category']
        f = request.files['file']
        if not f.filename.split('.')[1] in [
                'png', 'jpg', 'bmp', 'ico', 'jpeg', 'gif'
        ]:
            return render_template('product.html',
                                   title='Добавление товара',
                                   form=form,
                                   message='Неверный формат картинки')
        f = f.read()
        with open(f'static/img/file{count}.jpg', 'wb') as photo:
            photo.write(f)
        product.photo = str.encode(f'static/img/file{count}.jpg')
        current_user.product.append(product)
        db_sess.merge(current_user)
        db_sess.commit()
        return redirect('/')
    return render_template('product.html',
                           title='Добавление товара',
                           form=form)
Esempio n. 4
0
def product_add():
    categories = Category.query.all()

    product = Product()

    form = ProductForm(obj=product)

    # Set the categories to the form
    form.category_id.choices = [(c.id, c.name) for c in
                                Category.query.order_by('name')]

    if request.method == "POST":

        if form.validate():

            # populate Product obj with wtform data
            form.populate_obj(product)

            product.user_id = current_user.get_id()
            product.slug = slugify(product.title)

            f = form.picture.data

            # renames the file to prevent duplicated names
            filename = datetime.now().strftime(
                '%Y%m%d%H%M%S') + secure_filename(f.filename)

            filepath = os.path.join(
                app.config["UPLOAD_FOLDER"], 'uploads', filename
            )

            f.save(filepath)

            # @TODO Generate an image thumbnail

            product.picture = filename

            db_session.add(product)

            try:
                db_session.commit()
                flash('Nice! You just added your product to sell :D', 'success')
                redirect("/")
            except exc.SQLAlchemyError:
                db_session.rollback()
                flash('Error! There was an error trying to save your product',
                      'danger')

        else:
            for field, errors in form.errors.items():
                for error in errors:
                    flash(u"Error in the %s field - %s" % (
                        getattr(form, field).label.text,
                        error
                    ))

    return render_template(
        'products/add.html',
        categories=categories,
        form=form
    )
Esempio n. 5
0
def edit_product(id):
    form = ProductForm()
    db_sess = db_session.create_session()
    categories = db_sess.query(Category)
    category_flag = 'None'
    if request.method == "GET":
        product = db_sess.query(Product).filter(Product.id == id).first()

        if product:
            form.title.data = product.title
            picture = product.picture
            form.description.data = product.description
            category_obj = db_sess.query(Category).filter(
                Category.title == product.category).first()
            if not category_obj:
                category_obj = db_sess.query(Category).filter(
                    Category.id == product.category).first()
            category_flag = category_obj.title
            form.category.data = product.category
            form.producer.data = product.producer
            form.price.data = product.price
            form.count.data = product.count
            form.advantage.data = product.advantage
        else:
            abort(404)

    if form.validate_on_submit():
        db_sess = db_session.create_session()
        product = db_sess.query(Product).filter(Product.id == id).first()
        category_obj = db_sess.query(Category).filter(
            Category.title == product.category).first()
        if not category_obj:
            category_obj = db_sess.query(Category).filter(
                Category.id == product.category).first()
        category_flag = category_obj.title

        if product and current_user.is_admin:
            product.title = form.title.data

            if form.picture.data:
                # product.picture = form.picture.data
                f = form.picture.data
                parent_dir = path.dirname(path.abspath(__file__))
                basename = parent_dir + '\\static\\pictures\\pic'
                suffix = datetime.now().strftime("%y%m%d_%H%M%S")
                filename = "_".join([basename, suffix, '.png'])
                g = open(filename, 'wb')
                g.write(f.getbuffer())
                g.close()
                product.picture = '/static/pictures/pic_' + suffix + '_.png'

            product.description = form.description.data
            product.category = form.category.data
            product.producer = form.producer.data
            product.price = float(form.price.data)
            product.count = int(form.count.data)
            product.advantage = form.advantage.data
            db_sess.commit()
            return redirect('/')
        else:
            abort(404)
    # если у товара есть категория, значит он редактируется
    return render_template('product.html',
                           title='Редоктирование товара',
                           form=form,
                           categories=categories,
                           category=category_flag,
                           picture=picture)
Esempio n. 6
0
def edit_product(idi):
    form = ProductForm()
    if request.method == "GET":
        db_sess = db_session.create_session()
        product = db_sess.query(Product).filter(
            Product.id == idi, Product.user == current_user).first()
        if product:
            form.title.data = product.title.lower()
            form.content.data = product.content
            form.connection.data = product.connection
            form.category.data = product.category
            form.photo.data = product.photo
        else:
            abort(404)
    if request.method == "POST":
        db_sess = db_session.create_session()
        product = db_sess.query(Product).filter(
            Product.id == idi, Product.user == current_user).first()
        if form.submit.data:
            if product:
                product.title = form.title.data.lower()
                product.content = form.content.data
                product.connection = form.connection.data
                if not form.connection.data.isdigit() and str(
                        form.connection.data) != 11 and not str(
                            form.connection.data).startswith('8'):
                    return render_template(
                        'product.html',
                        title='Редактирование товара',
                        form=form,
                        message='Неверный формат ввода телефона',
                        delete=True)
                product.category = request.form['category']
                f = request.files['file']
                if not f.filename:
                    f = product.photo
                    with open(f.decode('utf-8'), mode='rb') as fi:
                        f = fi.read()
                elif not f.filename.split('.')[1] in [
                        'png', 'jpg', 'bmp', 'ico', 'jpeg', 'gif'
                ]:
                    return render_template('product.html',
                                           title='Редактирование товара',
                                           form=form,
                                           message='Неверный формат картинки',
                                           delete=True)
                else:
                    f = f.read()
                with open(f'static/img/file{idi - 1}.jpg', 'wb') as photo:
                    photo.write(f)
                product.photo = str.encode(f'static/img/file{idi - 1}.jpg')
                db_sess.commit()
                return redirect('/')
            else:
                abort(404)
        else:
            db_sess.delete(product)
            db_sess.commit()
            os.remove(f'static/img/file{product.id - 1}.jpg')
            return redirect('/')
    return render_template('product.html',
                           title='Редактирование товара',
                           form=form,
                           delete=True)