Beispiel #1
0
def create():
    product = ProductForm()
    register = RegisterForm()

    if not (register.validate_on_submit()) or not (
            product.validate_on_submit()):
        return redirect(url_for('editor.edit'))

    reg_user = register_user(register.data.get('email'),
                             register.data.get('password'))

    if not reg_user:
        return redirect(url_for('editor.edit'))

    if str(product.data.get('item_price')).endswith('.0') or str(
            product.data.get('item_price')):
        item_price = int(product.data.get('item_price'))
    else:
        item_price = product.data.get('item_price')

    add_product = Product(
        store_name=request.form.get('store_name'),
        item_name=product.data.get('item_name'),
        item_desc=product.data.get('item_desc'),
        item_currency=product.data.get('item_currency'),
        item_price=item_price,
        image=Uploads(request.files['item_img']).save_upload(),
        contact_email=product.data.get('contact_email')).create_product()

    if not add_product:
        return redirect(url_for('editor.edit'))

    Product.appendTable(reg_user, add_product)

    return redirect(url_for('seller.dashboard'))
Beispiel #2
0
def extract():
    form = ProductForm()
    if form.validate_on_submit():
        product_id = form.product_id.data
        scraper(product_id)
        return redirect(url_for('product', id=product_id))
    return render_template("extract.html", form=form)
Beispiel #3
0
def create_song(request, category_slug):
    """
    @param form:        the Form-object representation of product to render page   
    @param category:    the model representation of category of product     
    @param product:    the model representation of new product     
    @return:            the representation of detail category page(If the fields are filled) 
                            or create_product page(If the fields are empty)
    """
    form = ProductForm(request.POST or None, request.FILES or None)
    category = get_object_or_404(Category, slug=category_slug)
    context = {
        'category': category,
        'form': form,
    }
    if form.is_valid():
        products = category.product_set.all()
        for p in products:
            if p.name == form.cleaned_data.get("name"):
                context['error_message'] = 'You already added that product'
                return render(request, ADDRESS_CREATE_PRODUCT, context)
        product = form.save(commit=False)
        product.category = category
        product.save()
        return render(request, ADDRESS_DETAIL_CATEGORY, {'category': category})

    return render(request, ADDRESS_CREATE_PRODUCT, context)
Beispiel #4
0
def extract():
    form = ProductForm()
    if form.validate_on_submit():
        product_id = form.product_id.data
        scraper(product_id)
        return redirect(url_for('product', id=product_id))
    return render_template("extract.html", form=form

@app.route('/product/<id>')
def product(id):
    input_directory = "app/opinions_json"
    opinions = pd.read_json(input_directory+"/"+id+".json")
    return render_template(
        "product.html", 
        tables=[
            opinions.to_html(
                classes="table table-hover table-responsive",
                table_id = "opinions",
                index = False
            )
        ]
    )

@app.route('/products')
def products():
    input_directory = "app/opinions_json"
    products = [product.replace(".json","") for product in os.listdir(input_directory)]
    return render_template("products.html", products=products)
Beispiel #5
0
def create_product():

    user = current_user

    form = ProductForm()
    form['csrf_token'].data = request.cookies['csrf_token']

    flavours = []
    for x in range(1, 5):
        if request.form.get(f"flavour-{x}"):
            el = request.form.get(f"flavour-{x}")
            flavours.append(el)

    # find roaster id
    roaster = Roaster.query.filter(Roaster.user_id == user.id).first()

    if form.validate_on_submit():
        product = Product(name=form.data["name"],
                          roaster_id=roaster.id,
                          price=form.data["price"],
                          description=form.data["description"],
                          sweetness=form.data["sweetness"],
                          acidity=form.data["acidity"],
                          mouthfeel=form.data["mouthfeel"],
                          flavour=flavours)
        db.session.add(product)
        db.session.commit()
        return product.to_dict(), 201
    return {"errors": validation_errors_to_error_messages(form.errors)}, 400
Beispiel #6
0
def index():
    form = ProductForm()
    products = Product.query.all()
    context = {
        "name": "Derek",
        "title": "Home",
        "form": form,
        "products": products
    }
    if form.validate_on_submit():
        basedir = os.path.abspath(
            os.path.dirname(__file__)) + '/static/products/uploads/'
        filename = ''.join([str(random.randint(0, 9))
                            for i in range(0, 9)]) + '.png'
        print(basedir + filename)
        if not os.path.exists(basedir):
            os.makedirs(basedir)
        product = Product(name=form.name.data,
                          price=form.price.data,
                          inventory=form.inventory.data)
        product.image = filename
        form.image.data.save(basedir + filename)
        flash("Product created!")
        db.session.add(product)
        db.session.commit()
        return redirect(url_for('index'))
    return render_template("index.html", **context)
Beispiel #7
0
def upload_product():
    form = ProductForm()
    if request.method == 'POST':
        file = request.files['violin_product']
        print(file.filename)
        path = (os.path.join(app.config['UPLOAD_FOLDER'], file.filename))
        file.save(path)
        #return redirect(url_for('uploaded_product',filename=filename))

        # check if the post request has the file part
        if 'violin_product' not in request.files:
            flash('No file part')
            return redirect(request.url)

        # if user does not select file, browser also
        # submit an empty part without filename
        if file.filename == '':
            flash('No selected file')
            return redirect('upload_product')

        if form.validate_on_submit():
            product = Violin(product_images=file.filename,
                             product_name=form.product_name.data,
                             price=form.product_price.data)
            db.session.add(product)
            db.session.commit()
            flash('Your picture has been created!', 'success')
            return redirect(url_for('view_product'))
    return render_template("create_product.html", form=form)
Beispiel #8
0
def add_product():

    if session["user_type"] != "Klient":
        form = ProductForm()
        form2 = DeleteUserForm()
        if request.method == "POST":
            cur = get_db().cursor()
            form.validate_on_submit()
            cur.execute(
                "insert into Produkt values (null, ?, ?, ?, ?)",
                (
                    form.name.data,
                    form.net_price.data,
                    form.vat.data,
                    request.getlist("przycisk")[0],
                ),
            )
            get_db().commit()
            return redirect(url_for("products"))
        cur = get_db().cursor()
        cur.execute("Select id, imie, nazwisko from Osoba")
        return render_template("html/add_product.html.j2",
                               form=form,
                               persons=cur.fetchall(),
                               form2=form2)
    return redirect(url_for("index"))
Beispiel #9
0
def edit(product_id):
    product = Product.query.get_or_404(product_id)
    form = ProductForm(obj=product)
    if form.validate_on_submit():
        product.name = form.name.data
        product.description = form.description.data
        db.session.add(product)
        db.session.commit()
        return redirect(url_for('.details', product_id=product.id))
    return render_template('products/edit.html', form=form, product=product)
Beispiel #10
0
def update(request, id):
    if not request.user.is_authenticated:
        return render(request, 'app/Admin/signin.html')
    else:
        product = Product.objects.get(id=id)
        form = ProductForm(request.POST, instance=product)
    if form.is_valid():
        form.save()
        return redirect("/show")
    return render(request, 'app/Admin/datatable.html', {'product': product})
Beispiel #11
0
def products():
    form = ProductForm()
    shop_session = sfy.Session(session['shop_url'], '2019-04', session['token'])
    # activate the shopify session to use resources.
    sfy.ShopifyResource.activate_session(shop_session)
    if request.method == 'POST':
        if form.validate_on_submit():
            # generate_fake_customer_data(form.number_of_customers_field.data)
            create_fake_products_and_variants(form.number_of_products_field.data, 5)

    return render_template('products.html', form=form)
Beispiel #12
0
def extract():
    form = ProductForm()
    if form.validate_on_submit():
        product_id = form.product_id.data
        page_respons = requests.get("https://www.ceneo.pl/"+product_id)
        if page_respons.status_code == requests.codes['ok']:
            product = Product(product_id)
            product.extract_product()
            product.save_product()
            return redirect(url_for("product", id=product_id))
        else:
            form.product_id.errors.append("Podana wartość nie jest poprawnym kodem ptoduktu.")
    return render_template("extract.html", form=form)
Beispiel #13
0
def extract():
    form = ProductForm()
    if form.validate_on_submit():
        product_id = form.product_id.data
        page_respons = requests.get('https://www.ceneo.pl/'+product_id)
        if page_respons.status_code == requests.codes['ok']:
            product = Product(product_id)
            product.extract_product
            product.save_product
            return redirect(url_for('product', id=product_id))
        else:
            form.product_id.errors.append('Podana wartość nie jest poprawnym kodym produktu w serwisie Ceneo.')
    return render_template('extract.html', form=form)
Beispiel #14
0
def extraction():
    form = ProductForm()
    if form.validate_on_submit():
        page_response =  requests.get("https://www.ceneo.pl"+request.form['product_code'])
        if page_response.status_code == 200:
            product = Product(request.form['product_code'])
            product.extract_product()
            product.save_product()
            return redirect(url_for(product, product_id=product.product_id))
        else:
            form.product_code.errors.append("Dla podanego kodu nie ma produktu")
            return render_template("extraction.html", form=form)             
    return render_template("extraction.html", form=form)
def ArticleUpdate(request, slug):
    product = get_object_or_404(Product, slug=slug)
    form = ProductForm(instance=product,
                       data=request.POST or None,
                       files=request.FILES or None)
    if request.user != product.user:
        return HttpResponseForbidden()

    if form.is_valid():
        product.update()
        return HttpResponseRedirect(reverse('details', kwargs={'slug': slug}))
    context = {'form': form, 'product': product}
    return render(request, 'BlogTemplate/article_update.html', context=context)
Beispiel #16
0
def add_product(company):
    compname = Company.query.filter_by(company_name=company).first()
    form = ProductForm()
    if form.validate_on_submit():
        product = Product(name=form.name.data,
                          description=form.description.data,
                          manf_id=form.company.data)
        db.session.add(product)
        db.session.commit()
        flash('Successfully added product')
        return redirect(url_for('home'))
    if request.method == 'GET':
        form.company.data = compname.id
    return render_template('add_product.html', form=form)
Beispiel #17
0
def add_product():
    form = ProductForm()
    if form.validate_on_submit():
        if form.photo_url.data:
            photo_filename = save_photo(form.photo_url.data)
        product = Product(name=form.name.data,
                          description=form.description.data,
                          price=form.price.data,
                          photo_url=photo_filename)
        db.session.add(product)
        db.session.commit()
        flash('Product created successfully!', 'success')
        return redirect(url_for('products'))
    return render_template('add_product.html', title='Add Product', form=form)
Beispiel #18
0
def create():
    form = ProductForm()
    if form.validate_on_submit():
        price = form.price.data or 0
        product = Product(name=form.name.data,
                          description=form.description.data,
                          price_cents=int(price*100),
                          picture_url=form.picture_url.data,
                          creator=current_user,
                          store=current_user.store)
        db.session.add(product)
        db.session.commit()

        return redirect(url_for('products.details', product_id=product.id))
    return render_template('products/create.html', form=form)
Beispiel #19
0
def admin():
    context = { 
        'form': ProductForm()
    }
    form = ProductForm()
    if form.validate_on_submit():
        filename = time.strftime("%Y%m%d%H%M%S") + '.png'
        new_product = Product(name=form.name.data, image=filename, price=form.price.data, inventory=form.inventory.data,pr_type=form.pr_type.data, description=form.description.data)
        file = request.files['image']
        file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        db.session.add(new_product)
        db.session.commit()
        flash("Added new product to database")
        return redirect(url_for('admin'))
    return render_template('admin.html', **context)
Beispiel #20
0
def newproduct():
    form = ProductForm()
    if form.validate_on_submit():
        f = form.image.data
        filename = secure_filename(f.filename)
        save_url = os.path.join('app', 'static', filename)
        f.save(save_url)
        product = Product(name=form.name.data,
                          price=float(form.price.data),
                          stock=form.stock.data,
                          seller_id=current_user.id,
                          image_url=filename)
        db.session.add(product)
        db.session.commit()
        return redirect(url_for('user', username=current_user.username))
    return render_template('newproduct.html', form=form)
Beispiel #21
0
def create_entry(x):
    w = x
    cliform = ClientForm()
    proform = ProductForm()
    addform = AddsForm()
    patform = PathForm()
    wriform = WritingForm()
    heaform = HeadForm()
    errors = None
    if request.method == 'POST':
        wb = load_workbook('order.xlsx')
        entrys(cliform)
        fill_clear(wb)
        fill_cli(cliform, wb)
        fill_pro(proform, wb)
        fill_adds(addform, wb)
        fill_hea(heaform, wb)
        fill_wri(wriform, wb)
        fill_pat(patform, wb)
        fill_img(w, wb)

        wb.save(filename='order.xlsx')

        return redirect(url_for('index'))
    return render_template("order.html",
                           cliform=cliform,
                           proform=proform,
                           addform=addform,
                           patform=patform,
                           wriform=wriform,
                           heaform=heaform,
                           w=w,
                           errors=errors)
Beispiel #22
0
def product():
    form = ProductForm()
    if request.method == 'POST':
        product = Product(name=form.name.data)
        db.session.add(product)
        db.session.commit()
    products = Product.query.all()
    return render_template('home.html', products=products, form=form)
Beispiel #23
0
def add_product():
    if not current_user.is_authenticated:
        return redirect(url_for('login'))
    # add product to database

    # declare the Product Form
    form = ProductForm(request.form)
    form.product_type.choices = [(x.id, x) for x in Producttype.query.all()]
    msg = None

    if request.method == 'GET':
        form.process()
        return render_template('layouts/default.html',
                               content=render_template(
                                   'pages/add-product.html',
                                   form=form,
                                   message=msg))
    print(request.form)
    # check if both http method is POST and form is valid on submit
    if form.validate_on_submit():
        # assign form data to variables
        name = request.form.get('name', '', type=str)
        product_type = request.form.get('product_type', '', type=int)
        description = request.form.get('description', '', type=str)
        imageurl = request.form.get('imageurl', '', type=str)
        # see if product already exists
        product = Product.query.filter_by(name=name,
                                          producttype_id=product_type).first()
        #
        if product:
            flash(f'Error: A product named {product.name} already exists!')
        else:
            product = Product(name, description, product_type)
            product.save()
            flash(
                f'{name} successfully created! Return to product page or add another product.'
            )
    else:
        print(form.e)
        flash('I am sorry but the details you entered cannot be saved')

    return render_template('layouts/default.html',
                           content=render_template('pages/add-product.html',
                                                   message=msg,
                                                   form=form))
Beispiel #24
0
def index():
    form = ProductForm()

    products = Product.query.all()

    return render_template('index.html',
                           title='Inventory',
                           form=form,
                           products=products)
Beispiel #25
0
def extract():
    form = ProductForm()
    if form.validate_on_submit():
        page_response = requests.get("https://www.ceneo.pl/" +
                                     request.form["product_code"])
        print("problem " + str(page_response.status_code))
        print(str(form.product_code))
        if page_response.status_code == 200:
            product = Product(request.form['product_code'])
            product.extract_product()
            product.save_product()
            return redirect(url_for("product", product_id=product.product_id))
        else:
            form.product_code.errors.append(
                "Dla podanego kodu nie ma produktu")
            return render_template("extract.html", form=form)
        # return "Przesłano formularz"
    return render_template("extract.html", form=form)
Beispiel #26
0
def dashboard():
    usr = User().custom_query('user_id', current_user.get_id()).first()

    return render_template('/seller/dashboard.html',
                           form=ProductForm(),
                           store=StoreUrl(),
                           usr=usr,
                           message=get_flashed_messages(),
                           orders=Order().custom_query(
                               'user_id', current_user.get_id()).all())
Beispiel #27
0
def edit_product(id):
    if not current_user.is_authenticated:
        return redirect(url_for('login'))
    # declare the Product Form
    form = ProductForm(request.form)
    msg = None
    # print (current_user)
    # check if product already exists
    product = Product.query.filter_by(id=id).first()

    # update select component value
    form.product_type.default = product.producttype_id
    form.product_type.choices = [(x.id, x.name)
                                 for x in Producttype.query.all()]

    if request.method == 'GET':
        form.process()
        return render_template('layouts/default.html',
                               content=render_template(
                                   'pages/edit-product.html',
                                   form=form,
                                   product=product,
                                   message=msg))
    # check if both http method is POST and form is valid on submit
    if form.validate_on_submit():
        # assign form data to variables
        name = request.form.get('name', '', type=str)
        product_type = request.form.get('product_type', '', type=int)
        description = request.form.get('description', '', type=str)
        imageurl = request.form.get('imageurl', '', type=str)
        # if the requested product exists
        if product:
            product.name = name
            product.producttype_id = product_type
            product.description = description
            db.session().commit()
            flash(f'{name} successfully edited!')
        else:
            flash(f'Error: A product named {product.name} does not exist!')
    else:
        flash('I am sorry but the details you entered cannot be saved')
    return redirect('/psalm2vs8/products')
Beispiel #28
0
def save():
    log(log.INFO, '/product_save')
    form = ProductForm(request.form)
    if form.validate_on_submit():
        if form.id.data > 0:
            product = Product.query.filter(Product.id == form.id.data).first()
            if product is None:
                flash("Wrong product id.", "danger")
                return redirect(url_for('main.products'))
            for k in request.form.keys():
                product.__setattr__(k, form.__getattribute__(k).data)
        else:
            product = Product(name=form.name.data, status=form.status.data)
        product.save()
        log(log.INFO, "Product-{} was saved".format(product.id))
        return redirect(url_for('main.products', id=product.id))
    else:
        flash('Form validation error', 'danger')
        log(log.WARNING, "Form validation error")
    return redirect(url_for('product.edit', id=form.id.data))
Beispiel #29
0
def sell(request):
    """ Handles adding a new product by user

    Arguments:
        request -- [standard Django request arg]

    Returns:
        redirect -- on success go back to home page
        render -- render the sell html page with correct f
    """
    if request.method == "POST":
        post_data = request.POST.dict()
        profile = UserProfile.objects.get(user=request.user)
        post_data['seller'] = profile
        product_form = ProductForm(request.POST, request.FILES, post_data)
        if product_form.is_valid():
            product = product_form.save(commit=False)
            product.seller = profile
            product.save()
            logger.info("Product registered (sell): %s", product)
            return redirect(reverse("app:index"))
        else:
            print(product_form.errors)
            logger.info("Product registered (sell) failed: %s",
                        product_form.errors)
    else:
        product_form = ProductForm()
        logger.info("Product form rendered")

    return render(request, "app/sell.html", context={
        "form": product_form,
    })
Beispiel #30
0
def addproduct(request):
    if request.method == "POST":
        form = ProductForm(request.POST, request.FILES)
        form.save()
        return redirect('/product')
    else:
        form = ProductForm()
    return render(request, 'addproduct.html', {'form': form})