def edit_product(id):
    product = Product.find_product(id)

    form = ProductForm()

    if form.validate_on_submit():
        new_product = Product(
            id=product.id,
            title=form.title.data,
            content=form.content.data,
            price=form.price.data
        )

        product.edit_product(new_product)
        flash(f'{form.title.data} has been updated!', 'success')
        return redirect(url_for('view_product', id=product.id))

    elif request.method == "GET":
        form.title.data = product.title
        form.content.data = product.content
        form.price.data = product.price

    return render_template(
        "product/edit_product.html",
        title="Edit Product", form=form,
        legend="Edit product"
    )
def editProduct(request, pk):
    edit = False

    if request.method == "POST":
        form = ProductForm(request.POST, request.FILES)
        if form.is_valid():
            product = form.save(commit=False)

            photo = request.FILES['Photo']
            fs = FileSystemStorage()
            filename = fs.save(photo.name, photo)
            uploaded_file_url = fs.url(filename)

            product.Photo = uploaded_file_url
            product.id = pk
            product.save()
            edit = True
        else:
            product = Product.objects.get(id=pk)
            product.Title = form.data['Title']
            product.Description = form.data['Description']
            product.Price = form.data['Price']
            product.save()
            edit = True

    args = {}
    args['user'] = auth.get_user(request)
    args['form'] = ProductForm(instance=Product.objects.get(id=pk))
    args['whatEdit'] = 'Редагування продукції'

    if not edit:
        return render(request, 'edit.html', args)
    else:
        args['products'] = Product.objects.all()
        return render(request, 'products.html', args)
Exemple #3
0
def cliProductos():
    if 'username' in session:
        formulario = ProductForm()
        if formulario.validate_on_submit():
            producto = formulario.producto.data.upper()
            if len(producto) < 3:
                flash(
                    'Debe ingresar al menos 3 caracteres para realizar la búsqueda.'
                )
                return render_template('cliProductos.html', form=formulario)
            else:
                listaProductos = buscarProductos(registrosventas, producto)
                if len(listaProductos) == 0:
                    flash('No existen productos con la descripción ingresada.')
                elif len(listaProductos) == 1:
                    listaClientes = listadoCliProductos(
                        registrosventas, producto)
                    return render_template(
                        'cliProductos.html',
                        form=formulario,
                        listaClientes=listaClientes,
                        producto=formulario.producto.data.upper())
                else:
                    flash(
                        'Se encontró mas de un producto, por favor seleccione el que desea consultar.'
                    )
                    return render_template('cliProductos.html',
                                           form=formulario,
                                           productos=listaProductos)
        return render_template('cliProductos.html', form=formulario)
    else:
        flash('Para poder acceder debe estar logueado.')
        return redirect(url_for('ingresar'))
    def test_title_unique(self):
        self.product['title'] = 'My Book Title'
        f = ProductForm(self.product)
        self.assertFalse(f.is_valid())
        self.product['title'] = 'My Another Book Title'

        
Exemple #5
0
 def test_attrs_cannot_empty(self):
     f = ProductForm({})
     self.assertFalse(f.is_valid())
     self.assertTrue(f['title'].errors)
     self.assertTrue(f['description'].errors)
     self.assertTrue(f['price'].errors)
     self.assertTrue(f['imageUrl'].errors)
Exemple #6
0
def add_edit(request, id=None):
    obj = None
    if id:
        obj = get_object_or_404(Product, pk=id)

    if request.method == "POST":
        form = ProductForm(request.POST, instance=obj)
        if form.is_valid():
            form.save()
            messages.success(request, 'Record has been saved successfully.')
            if id:
                return HttpResponseRedirect(reverse("internal:products:index"))
            return HttpResponseRedirect(".")
        else:
            messages.error(request, 'Failed to save record. Please correct the errors below.', extra_tags='danger')
    else:
        form = ProductForm(instance=obj)

    context = {
        'page_header': ("Edit Product ID: %s" % id) if id else "Add New Product",
        'page_title': ("Edit Product ID: %s" % id) if id else "Add New Product",
        'form': form
    }

    return render(
        request,
        'products/add_edit.html',
        context
    )
Exemple #7
0
 def test_attrs_cannot_empty(self):
     f = ProductForm({})
     self.assertFalse(f.is_valid())
     self.assertTrue(f['title'].errors)
     self.assertTrue(f['description'].errors)
     self.assertTrue(f['price'].errors)
     self.assertTrue(f['image_url'].errors)
Exemple #8
0
def product_register():
    form = ProductForm()
    if request.method == "POST" and form.validate():
        name = form.name.data
        brand = form.brand.data
        style = form.style.data
        abv = form.abv.data
        ibu = form.ibu.data
        estcal = form.estcal.data
        c, conn = connection()

        x = c.execute("SELECT * FROM beer WHERE name LIKE %s", [thwart(name)])

        if int(x) > 0:
            flash("That beer is already in the system, please choose another.")
            return render_template("product_register.html", form=form)

        else:
            c.execute(
                "INSERT INTO beer (name, brandName, Style, abv, ibu, estCal) VALUES (%s, %s, %s, %s, %s, %s)",
                (thwart(name), thwart(brand), thwart(style), thwart(
                    str(abv)), thwart(str(ibu)), thwart(str(estcal))))

            conn.commit()
            flash("Thanks for registering your beer!")
            c.close()
            conn.close()
            gc.collect()

            return redirect(url_for("homepage"))

    return render_template("product_register.html", form=form)
Exemple #9
0
def show_cat(cat_id):
    prodForm=ProductForm()
    prods = Product.query.filter_by(category = Category.query.get(cat_id)).all()
    cat = Category.query.get(cat_id)
    prodForm.category.default=cat.name
    prodForm.process()
    return render_template('shopapp/category.html',prods=prods,prodForm=prodForm,cat=cat)
Exemple #10
0
def new_product(request, pk):
    form = ProductForm()

    business_profile = get_object_or_404(BusinessProfile, pk=pk)

    if request.method == 'POST' and request.user.is_authenticated():
        form = ProductForm(request.POST)
        if form.is_valid():
            # check for duplicates
            # check_duplicates(Product, 
            #                  form.cleaned_data['name'], 
            #                  form.cleaned_data['product_size'],
            #                  business_profile)

            product = form.save()
            # attribute "business profile" to product
            product.business_profile = business_profile
            product.save()

            messages.add_message(request, messages.INFO,
                "You've created a product successfully. Please add raw materials used.")

            return redirect('product_add_raw_material', pk=pk, id=product.id) #, id=product.id)

        else:
            # TODO -> handel errors here!
            pass

    return render_to_response('dashboard/new_product.html',
        {'form': form},
        RequestContext(request)
        )
Exemple #11
0
def admin_products():
    if not g.user:
        return redirect('/')

    else:
        products = Product.query.all()
        form = ProductForm()
        #add product to db
        if form.validate_on_submit():
            product = Product.form_to_model(form)
            #converting images into bytes like object
            #prepare images to be stored
            product.prepare_to_store()
            db.session.add(product)
            db.session.commit()

            flash('Product added to database', 'success')
            return redirect(f'/{get_route()}/view-products')

        else:

            for product in products:
                if product.available:
                    product.availabile = 'Available'
                else:
                    product.availabile = 'Sold'
            for product in products:
                product.prepare_to_show()
            organized_products = Helper.organize_products(products)
            return render_template('view-products.html',
                                   form=form,
                                   rows=organized_products,
                                   route=get_route())
Exemple #12
0
def edit_product(request, id):
    product_instance = Product.objects.get(id=id)
    form = ProductForm(request.POST or None, instance=product_instance)
    if form.is_valid():
        form.save()
    return render_to_response("edit_product.html",
                              locals(),
                              context_instance=RequestContext(request))
Exemple #13
0
def share():
    if request.method == 'GET':
        form = ProductForm()
    else:
        form = ProductForm(request.form)
        if form.validate():
            if form.create_product(g.user) is not None:            
                return redirect(url_for('home'))    
    return render_template('share_product.html', form=form)
Exemple #14
0
 def test_product_form(self):
     form = ProductForm({
         'category': 'sale',
         'sku': '111111',
         'name': 'test',
         'description': 'Test Description',
         'price': '10',
     })
     self.assertFalse(form.is_valid())
Exemple #15
0
def edit(request, pk):
    pd1 = get_object_or_404(Product,pk=id)
    form = ProductForm(request.POST or None, instance = pd1)

    if form.is_valid():
        form.save()
    t=get_template('ebook/forms.html')
    c=RequestContext(request,locals())
    return HttpResponse(t.render(c))
Exemple #16
0
def product_create():
    """Provide HTML form to create a new product."""
    form = ProductForm(request.form)
    if request.method == 'POST' and form.validate():
        mongo.db.products.insert_one(form.data)
        # Success. Send user back to full product list.
        return redirect(url_for('products_list'))
    # Either first load or validation error at this point.
    return render_template('product/edit.html', form=form)
Exemple #17
0
def show_cat(cat_id):
    prodForm = ProductForm()
    prods = Product.query.filter_by(category=Category.query.get(cat_id)).all()
    cat = Category.query.get(cat_id)
    prodForm.category.default = cat.name
    prodForm.process()
    return render_template('shopapp/category.html',
                           prods=prods,
                           prodForm=prodForm,
                           cat=cat)
Exemple #18
0
def product_edit(product_id):
  form = ProductForm(request.form)
  product = mongo.db.products.find_one({ "_id": ObjectId(product_id) })

  if request.method == 'POST' and form.validate():
    mongo.db.products.replace_one({"_id": ObjectId(product_id)}, form.data)
    # Success. Send user back to full product list.
    return redirect(url_for('products_list'))
  # Either first load or validation error at this point.
  return render_template('product/edit_product.html', product=product, form=form)
Exemple #19
0
 def setUp(self):
   self.product = {
   'title':'My Book Title',
   'description':'yyy',
   'image_url':'http://google.com/logo.png',
   'price':1
   }
   f = ProductForm(self.product)
   f.save()
   self.product['title'] = 'My Another Book Title'
Exemple #20
0
 def setUp(self):
     self.product = {
         'title': 'My Book Title',
         'description': 'yyy',
         'image_url': 'http://google.com/logo.png',
         'price': 1
     }
     f = ProductForm(self.product)
     f.save()
     self.product['title'] = 'My Another Book Title'
Exemple #21
0
def admin():
    form = LoginForm()
    prod = ProductForm()
    if prod.validate_on_submit():
        new = Product(name=prod.name.data, stock=prod.stock.data, image=prod.image.data, price=prod.price.data)
        db.session.add(new)
        db.session.commit()
        flash('Product Added!')
        return redirect(url_for('store'))
    return render_template('admin.html', prod=prod, form=form)
Exemple #22
0
def new_product():
    form = ProductForm()
    if session['whois'] == '2':
        if form.validate_on_submit():
            material = dict(MATERIAL_CHOICES)[form.material.data]
            if form.photo.data:
                picture_file = save_picture(form.photo.data)
            mycursor.execute(
                'SELECT * FROM product WHERE store_id = %s AND product_name = %s',
                (
                    session['id'],
                    form.name.data,
                ))
            exist_product = mycursor.fetchone()
            if exist_product:
                flash("There already exists this product in your store!",
                      'warning')
                return redirect(url_for('new_product'))
            else:
                if form.photo.data:
                    now = datetime.datetime.utcnow()
                    mycursor.execute(
                        'INSERT INTO product(store_id, product_name, material_type, price, color, changing_date, photo) VALUES (%s, %s, %s, %s, %s, %s, %s)',
                        (
                            session['id'],
                            form.name.data,
                            material,
                            form.price.data,
                            form.color.data,
                            now.strftime('%Y-%m-%d %H:%M:%S'),
                            picture_file,
                        ))
                    mydb.commit()
                else:
                    now = datetime.datetime.utcnow()
                    mycursor.execute(
                        'INSERT INTO product(store_id, product_name, material_type, price, color, changing_date) VALUES (%s, %s, %s, %s, %s, %s)',
                        (
                            session['id'],
                            form.name.data,
                            material,
                            form.price.data,
                            form.color.data,
                            now.strftime('%Y-%m-%d %H:%M:%S'),
                        ))
                    mydb.commit()
                flash("New product added!", 'success')
                return redirect(url_for('home'))
        return render_template('new_product.html',
                               title='New Product',
                               form=form,
                               legend='Add Product')
    else:
        flash("Firstly, you need to create a virtual store!", 'warning')
        return redirect(url_for('home'))
Exemple #23
0
def new(request):
    form = ProductForm(request.POST or None)

    if request.method == "POST":
        form = ProductForm(request.POST)
        if form.is_valid():
            pd1 = form.save(created_by=request.user)
            return redirect('product_last')
    t = get_template('ebook/form.html')
    c = RequestContext(request,locals())
    return HttpResponse(t.render(c))
Exemple #24
0
def product_edit(product_id):
    # return 'Form to edit product #.'.format(product_id)
    """Provide HTML form to edit an existing product."""
    product = MONGO.db.products.find_one({"_id": ObjectId(product_id)})
    form = ProductForm(request.form)
    if request.method == 'POST' and form.validate():
        MONGO.db.products.replace_one({'_id': ObjectId(product_id)}, form.data)
        # Success. Send user back to full product list.
        return redirect(url_for('products_list'))
    # Either first load or validation error at this point.
    return render_template('product/edit.html', form=form, product=product)
Exemple #25
0
def edit_product(id):
    """Return page showing all the products has to offer"""
    check_admin()
    add_product = False
    product = Product.query.get_or_404(id)
    form = ProductForm(obj=product)
    if form.validate_on_submit():
        filename = secure_filename(form.upload.data.filename)
        src = UPLOADPATH + filename
        form.upload.data.save(src)
        filemd5 = hashlib.md5()

        with open(UPLOADPATH + filename, 'rb') as f:
            for chunk in iter(lambda: f.read(4096), b""):
                filemd5.update(chunk)
        if form.available.data:
            in_stock = True
        else:
            in_stock = False
        dst = P_IMAGEPATH + filemd5.hexdigest() + '.' + filename.split('.')[1]
        if Product.query.filter_by(imgurl=filemd5.hexdigest() + '.' +
                                   filename.split('.')[1]).first() == None:

            product = Product.query.filter_by(id=id).first()
            product.common_name = form.common_name.data
            product.price = form.price.data
            orgfilename = P_IMAGEPATH + product.imgurl
            product.imgurl = filemd5.hexdigest() + '.' + filename.split('.')[1]
            product.color = form.color.data
            product.size = form.size.data
            product.available = in_stock
            product.catalog_id = Catalog.query.filter_by(
                catalog_name=str(form.catalog_id.data)).first().id
            db.session.commit()
            flash('Update product successfull.')
            copyfile(src, dst)
            os.remove(src)
            os.remove(orgfilename)
        else:
            os.remove(src)
            flash('Upload image file was in used.')
        #os.remove(os.getcwd() + '\\static\\product\\images\\'+orgfilename)
        # redirect to the departments page
        return redirect(url_for('admin.products', page=1))
    # pre setting value
    form.catalog_id.data = product.product_type
    catalogs = Catalog.get_all()
    return render_template('admin/product.html',
                           action="Edit",
                           add_product=add_product,
                           form=form,
                           product=product,
                           catalogs=catalogs,
                           title="Edit Product")
Exemple #26
0
def editProduct(prod_id):
    prodForm = ProductForm()
    prod = Product.query.get(prod_id)
    if prodForm.validate_on_submit():
        prod.name=prodForm.name.data
        prod.category = prodForm.category.data
        prod.note=prodForm.note.data
        prod.size = prodForm.size.data
        prod.unit=prodForm.unit.data
        db.session.commit()
    return redirect(url_for('shopapp.shop_main'))
Exemple #27
0
def editProduct(prod_id):
    prodForm = ProductForm()
    prod = Product.query.get(prod_id)
    if prodForm.validate_on_submit():
        prod.name = prodForm.name.data
        prod.category = prodForm.category.data
        prod.note = prodForm.note.data
        prod.size = prodForm.size.data
        prod.unit = prodForm.unit.data
        db.session.commit()
    return redirect(url_for('shopapp.shop_main'))
Exemple #28
0
def product_edit(product_id):
    """Provide HTML form to edit a product."""
    form = ProductForm(request.form)
    if request.method == 'POST' and form.validate():
        
        mongo.db.products.update_one({'_id':ObjectId(product_id)},{'$set':{'name':request.form['name'], 'description':request.form['description'], 'price':request.form['price']}})
        
        # Success. Send user back to full product list.
        return redirect(url_for('products_list'))
    # Either first load or validation error at this point.
    return render_template('product/edit.html', form=form)
Exemple #29
0
def product_edit(product_id):
    """Provide HTML form to edit a given product."""
    product = mongo.db.products.find_one({"_id": ObjectId(product_id)})
    if product is None:
        abort(404)
    form = ProductForm(request.form, data=product)
    if request.method == 'POST' and form.validate():
        mongo.db.products.replace_one(product, form.data)
        # Success. Send the user back to the detail view.
        return redirect(url_for('products_list'))
    return render_template('product/edit.html', form=form)
Exemple #30
0
def my_products(request):
    user = request.user
    if request.method == 'POST':
        form = ProductForm(request.POST)
        if form.is_valid():
            form.save()
    else:
        form = ProductForm()
    companies = Company.objects.filter(owner=user)
    products = Product.objects.filter(company__in=companies)
    exchange_rate = get_rate_of_exchange()
    return render(request, 'my_products.html', {'products': products, 'form': form, 'exchange_rate': exchange_rate})
Exemple #31
0
def my_product(request, slug=None):
    product = get_object_or_404(Product, slug=slug)
    if request.method == 'POST':
        form = ProductForm(request.POST)
        if form.is_valid():
            updated_product = form.save(commit=False)
            updated_product.id = product.id
            updated_product.created = product.created
            updated_product.save()
    else:
        form = ProductForm(instance=product)
    return render(request, 'my_product.html', {'form': form, 'product': product})
Exemple #32
0
def new_product():
    # add a new product
    form = ProductForm(request.form)

    if request.method == 'POST' and form.validate():
        # saving new product
        product = Master()
        save_changes(product, form, new=True)
        flash('New product added successfully!')
        return redirect('/')

    return render_template('new_product.html', form=form)
Exemple #33
0
def admin_products(request):
    if request.method == 'POST':
        form = ProductForm(request.POST, request.FILES)
        if form.is_valid():
            create_product(request)
        else:
            print form.errors
    if not request.user or not request.user.is_staff:
        return redirect('login')
    categories = ['Камеры', 'Антирадары']
    brands = ['Nikon', 'Canon', 'Fujitsu']
    return render(request, "core/admin/index.html", {"categories": categories, "brands": brands})
Exemple #34
0
def add_product():
    """Return page showing all the products has to offer"""
    check_admin()
    add_product = True
    form = ProductForm()
    if form.validate_on_submit():
        filename = secure_filename(form.upload.data.filename)
        src = UPLOADPATH + filename
        form.upload.data.save(src)
        filemd5 = hashlib.md5()

        with open(UPLOADPATH + filename, 'rb') as f:
            for chunk in iter(lambda: f.read(4096), b""):
                filemd5.update(chunk)
        if form.available.data:
            in_stock = True
        else:
            in_stock = False
        dst = P_IMAGEPATH + filemd5.hexdigest() + '.' + filename.split('.')[1]
        if Product.query.filter_by(imgurl=filemd5.hexdigest() + '.' +
                                   filename.split('.')[1]).first() == None:

            copyfile(src, dst)
            os.remove(src)
            product = Product(
                common_name=form.common_name.data,
                price=form.price.data,
                imgurl=filemd5.hexdigest() + '.' + filename.split('.')[1],
                color=form.color.data,
                size=form.size.data,
                available=in_stock,
                catalog_id=Catalog.query.filter_by(
                    catalog_name=str(form.catalog_id.data)).first().id)
            db.session.add(product)
            db.session.commit()
            flash('Add product successfull.')
        else:
            os.remove(src)
            flash('Upload image file was in used.')
        # redirect to the departments page
        return redirect(url_for('admin.products', page=1))

    # form.common_name.data = product.common_name
    # form.price.data = product.price
    catalogs = Catalog.get_all()
    products = Product.get_all()
    return render_template('admin/product.html',
                           action="Add",
                           add_product=add_product,
                           form=form,
                           products=products,
                           title="Edit Product",
                           catalogs=catalogs)
Exemple #35
0
def product_add(request):
  if request.method == 'POST':
    form = ProductForm(request.POST)
    if form.is_valid():
      p = form.save(commit=False)
      p.sn = generate_sn(prefix = 'PROD')
      p.save()
      serializer = JSONSimpleSerializer()
      return HttpResponse(serializer.serialize([p,], use_natural_foreign_keys=True))
  else:
    form = ProductForm()
    return render_to_response('modal/main_form.html',{'action':'Add', 'module':module, 'form': form},context_instance=RequestContext(request))
def new_product():
    form = ProductForm()
    if form.validate_on_submit():
         products_collection.insert_one({'title': form.title.data, 'author': form.author.data, 'editor': form.editor.data, 
                                        'year_published': form.year_published.data, 'price': form.price.data , 'quantity': form.quantity.data,
                                        'summary': form.summary.data})
         flash('Product created!', 'success')
         app.logger.info('Product Created Sucessfully')
         return redirect(url_for('home'))
    else: 
        app.logger.info('PRODUCT NOT CREATED, ERROR')
    return render_template('create_product.html', title='New Product', form=form, legend="Update Product")
Exemple #37
0
def newProduct():
    prodForm = ProductForm()
    name = prodForm.name.data
    if prodForm.validate_on_submit():
        if Product.query.filter_by(name=name).first():
            flash('Product with this name already exists!', 'alert-danger')
        else:
            prod = Product(name=name, category = prodForm.category.data, note=prodForm.note.data, size = prodForm.size.data, unit=prodForm.unit.data)
            db.session.add(prod)
            db.session.commit()
            return redirect(redirect_url())
    return redirect(url_for('shopapp.shop_main')) 
def update_product(product_title):
    product =  products_collection.find_one({"title": product_title})
    form = ProductForm()
    if form.validate_on_submit():
         products_collection.update( products_collection.find_one({"title": product_title}), {'title': form.title.data, 'author': form.author.data, 'editor': form.editor.data, 
                                        'year_published': form.year_published.data, 'price': form.price.data , 'quantity': form.quantity.data,
                                        'summary': form.summary.data})
         flash('Product updated!', 'success')
         app.logger.info('Product Updated Sucessfully')
         return redirect(url_for('home'))
    else:
        app.logger.info('PRODUCT NOT UPDATED, ERROR')
    return render_template('create_product.html', title='Update', form=form, legend="Update Product")
Exemple #39
0
def add_new_product():
    form = ProductForm()
    if form.validate_on_submit():
        new_product = Product(title=form.title.data,
                              description=form.description.data,
                              price=form.price.data,
                              img_url=form.img_url.data)
        db.session.add(new_product)
        db.session.commit()
        return redirect(url_for('index'))
    return render_template('new-product.html',
                           current_user=current_user,
                           form=form)
Exemple #40
0
def product_info(request, product_slug, template_name="pdcts/poduct_edit.html"):
#    request.breadcrumbs( ( ("My Account", '/accounts/my_account/'), ("Edit Profile", request.path_info) ) )
    if request.method == 'POST':
        form = ProductForm(request.POST, request.FILES)
        if form.is_valid():
            product_profile.set(request, product_slug)
            url = urlresolvers.reverse('my_account')
            return HttpResponseRedirect(url)
    else:
        pdct_profile = product_profile.retrieve(request, product_slug)
        form = ProductForm(instance=pdct_profile)
    page_title = 'Edit Product Information'
    return render_to_response(template_name, locals(), context_instance=RequestContext(request))
Exemple #41
0
def product_edit(product_id):
  # Query: get Product object by ID.
  product = mongo.db.products.find_one({ "_id": ObjectId(product_id) })
  if product is None:
    # Abort with Not Found.
    abort(404)
  form = ProductForm(request.form, name=product["name"], 
                    description=product["description"], price=product["price"])
  if request.method == 'POST' and form.validate():
    mongo.db.products.replace_one({ "_id": ObjectId(product_id) }, form.data)

    return redirect(url_for('products_list'))
  return render_template('product/edit.html', form=form)
def product_view():
    errors = []
    if request.method == 'POST':
        form = ProductForm(request.form)
        if form.validate():
            product = form.data
            products.append(product)
        else:
            for errors_list in form.errors.values():
                if type(errors_list) == list:
                    for error in errors_list:
                        errors.append(error)
    return render_template('products.html', products=products, errors=errors)
Exemple #43
0
 def test_price_positive(self):
   f = ProductForm(self.product)
   self.assertTrue(f.is_valid())
   self.product['price'] = 0
   f = ProductForm(self.product)
   self.assertFalse(f.is_valid())
   self.product['price'] = -1
   f = ProductForm(self.product)
   self.assertFalse(f.is_valid())
   self.product['price'] = 1
Exemple #44
0
  def test_imgae_url_endwiths(self):
    url_base = 'http://google.com/'
    oks = ('fred.gif', 'fred.jpg', 'fred.png', 'FRED.JPG', 'FRED.Jpg')
    bads = ('fred.doc', 'fred.gif/more', 'fred.gif.more')
    for endwith in oks:
      self.product['image_url'] = url_base+endwith
      f = ProductForm(self.product)
      self.assertTrue(f.is_valid(), msg='error when image_url endwith '+ endwith)

    for endwith in bads:
      self.product['image_url'] = url_base+endwith
      f = ProductForm(self.product)
      self.assertFalse(f.is_valid(), msg='error when image_url endwith '+ endwith)
      self.product['image_url'] = 'http://google.com/logo.png'
Exemple #45
0
def product_edit(product_id):
    product = mongo.db.products.find_one({"_id": ObjectId(product_id)})
    if product is None:
        # Abort with Not Found.
        abort(404)
    form = ProductForm(request.form)
    if request.method == 'GET':
        form.name.data = product.get('name')
        form.description.data = product.get('description')
        form.price.data = product.get('price')
        return render_template('product/edit.html', form=form)
    elif request.method == 'POST' and form.validate():
        mongo.db.products.replace_one({'name': product.get('name')}, form.data)
        return redirect(url_for('products_list'))
Exemple #46
0
def product_update(request):
  if request.method == 'POST':
    postdata = request.POST.copy()
    try:
      c = Product.objects.get(sn=postdata.pop('sn')[0])
    except Product.DoesNotExist:
      raise Http404
    form = ProductForm(postdata, instance=c)
    if form.is_valid():
      p = form.save()
      serializer = JSONSimpleSerializer()
      return HttpResponse(serializer.serialize([p,], use_natural_foreign_keys=True))
  else:
      return HttpResponse('Invalid request.')
Exemple #47
0
def edit_product(request, product_id=0):
    # Sets the form of product creation. If product_id is present, will use the product as form instance
    if product_id:
        try:
            product = Product.objects.get(pk=product_id)
            form = ProductForm(request.POST or None, instance=product)
        except Product.DoesNotExist:
            form = ProductForm(request.POST or None)
    else:
        form = ProductForm(request.POST or None)
    if form.is_valid():
        product = form.save()
        return HttpResponseRedirect(reverse("products.views.products_list"))
    return locals()
Exemple #48
0
def new_product():
    """
    Add a new product
    """
    form = ProductForm(request.form)

    if request.method == 'POST' and form.validate():
        # save the album
        product = Product()
        save_product(product, form, new=True)
        flash('Product created successfully!')
        return redirect('/sell')

    return render_template('new_product.html', form=form)
Exemple #49
0
def add_product():
    form = ProductForm()
    db_sess = db_session.create_session()
    res = db_sess.query(Category.Id, Category.Name).all()
    form.category.choices = [category[1] for category in res]
    if form.validate_on_submit():
        data.add_product(form.name.data,
                         form.description.data,
                         form.price.data,
                         form.count.data,
                         form.image,
                         form, res)
        return redirect("/add_product")
    return render_template('add_product.html', title='Добавление товара', form=form)
Exemple #50
0
def product_edit(product_id):
  product = mongo.db.products.find_one({ "_id": ObjectId(product_id) })
  if product is None:
    # Abort with Not Found.
    abort(404)
  form = ProductForm(request.form)
  
  if request.method == 'POST' and form.validate():
  	mongo.db.products.find_one_and_update({ "_id": ObjectId(product_id) }, { "$set": form.data })
  	return redirect(url_for('products_list'))

  form.name.data = product['name']
  form.description.data = product['description']
  form.price.data = product['price']
  return render_template('product/edit.html', form=form)
Exemple #51
0
 def get(self, product_id=None, **kwargs):
     """Return a product to edit or an empty form to create"""
     template = 'admin/product/new.html'
     files = get_files()
     #print self.form.photo.choices
     context = {
         'files': files,
         'form': self.form,
     }
     
     # render edit form
     if product_id is not None:
         product = Product.get_by_id(product_id)
         if product:
             self.form = ProductForm(obj=product)
             self.form.tags.data = ', '.join(product.tags)
             product_photo = ''
             if product.photo:
                 product_photo = product.photo.key().id()
             context.update({ 'form': self.form, 'product_photo': product_photo })
             template = 'admin/product/edit.html'
         else:
             return redirect('/admin/shop/')
     # render new form
     return self.render_response(template, **context)
Exemple #52
0
def new_product(request):
    if request.method == 'POST':
        form = ProductForm(request.POST, request.FILES)

        if form.is_valid():
            product = form.save(commit=False)
            product.seller = request.user
            product.save()

            request.session['message'] = 'Product successfully added'
            return HttpResponseRedirect('/')
    else:
        context = retrieve_basic_info(request)
        form = ProductForm()
        context['form'] = form
        return render(request, 'new_product.html', context)

    return render(request, 'new_product.html', {'form': form})
Exemple #53
0
class ProductHandler(BaseHandler):
    @admin_required
    def get(self, product_id=None, **kwargs):
        """Return a product to edit or an empty form to create"""
        template = 'admin/product/new.html'
        context = {
            'form': self.form,
        }
        # render edit form
        if product_id is not None:
            product = Product.get_by_id(product_id)
            if product:
                self.form = ProductForm(obj=product)
                self.form.tags.data = ', '.join(product.tags)
                context.update({ 'form': self.form })
                template = 'admin/product/edit.html'
            else:
                return redirect('/admin/shop/')
        # render new form
        return self.render_response(template, **context)
    
    @admin_required
    def post(self, product_id=None, **kwargs):
        """Handle submitted form data"""
        # validate form
        if self.form.validate():
            name = self.form.name.data
            description = self.form.description.data
            price = self.form.price.data
            unit = self.form.unit.data
            live = self.form.live.data
            tags = self.form.tags.data
            language = self.form.language.data
            if tags is not None:
                tags = [tag.strip() for tag in tags.split(',') if tag != '']
            # save edit form
            if product_id:
                product = Product.get_by_id(product_id)
                product.name = name
                product.description = description
                product.price = price
                product.unit = unit
                product.live = live
                product.tags = tags
                product.language = language
            # save new form
            else:
                product = Product(name=name, description=description, price=price, unit=unit, live=live, tags=tags, language=language)
            if product.put():
                return redirect('/admin/shop/products/')
        return self.get(**kwargs)
        
    @cached_property
    def form(self):
        """Form instance as cached_property"""
        return ProductForm(self.request)
Exemple #54
0
def create(request):
    if ( request.user.username=='' ):
        Uform = AnonymousForm(prefix='ano')
        Pform = ProductForm(prefix='prd')
        if request.method == 'POST':
            Pform = ProductForm(request.POST, request.FILES, prefix='prd')
            Uform = AnonymousForm(request.POST, prefix='ano')
            if Uform.is_valid() and Pform.is_valid():
                FileUploadHandler(request.FILES['image'])

                u = Uform.save()
                p = Pform.save()

                u.product_id = p.id

                u.save()

                return HttpResponseRedirect('/show/all/')
        else:
            Pform = ProductForm()
            Uform = AnonymousForm()
        args = {}
        args.update(csrf(request))
        args['Pform'] = Pform
        args['Uform'] = Uform
        return render_to_response('create_product_ano.html', args)

    else:
        if request.method == 'POST':
            form = ProductForm(request.POST, request.FILES)
            if form.is_valid():
                FileUploadHandler(request.FILES['image'])

                # u=User.objects.get(username=request.user.username)

                obj = form.save(commit=False)
                obj.user = request.user
                obj.save()
                return HttpResponseRedirect('/show/all/')
        else:
            form = ProductForm()

        args = {}
        args.update(csrf(request))
        args['form'] = form
        return render_to_response('create_product.html', args)
Exemple #55
0
 def get(self, product_id=None, **kwargs):
     """Return a product to edit or an empty form to create"""
     template = 'admin/product/new.html'
     context = {
         'form': self.form,
     }
     # render edit form
     if product_id is not None:
         product = Product.get_by_id(product_id)
         if product:
             self.form = ProductForm(obj=product)
             self.form.tags.data = ', '.join(product.tags)
             context.update({ 'form': self.form })
             template = 'admin/product/edit.html'
         else:
             return redirect('/admin/shop/')
     # render new form
     return self.render_response(template, **context)
Exemple #56
0
def add_product (request, template_name="pdcts/add.html"):
        request.breadcrumbs(("Submit a Product"),request.path_info)
	page_title = 'Submission'

    	'''try:
        	profile = request.user.get_profile()
    	except UserProfile.DoesNotExist:
       		profile = UserProfile(user=request.user)
        	profile.save() '''

	if request.method =='POST':
		form = ProductForm (request.POST, request.FILES)

		email_subject = 'Approve a Product'
		email_body = "Hello Administrator, \n\nThis is a My Campuser alert for products that have been submitted and are awaiting your approval.\n\nLogin to the admin panel to activate/approve these products\n\nRegards,\nMy Campuser Team"

		if form.is_valid():
			add = form.save(commit=False)
			add.user = request.user
			product_name = request.POST.get('product_name')
			add.product_name = product_name.title()
			add.save()
			form.save_m2m()
			send_mail(email_subject, email_body, '*****@*****.**' , ['*****@*****.**'])

	             	reputation = User_Reputation.objects.filter(user = request.user)

	             	if reputation:
				r = User_Reputation.objects.get(user = request.user)
				nR = r.reputation
	              	else:
		   		r = User_Reputation()
		              	r.user = request.user
		             	r.reputation = 0.5
		                r.entity_alpha = 0.5
		               	r.entity_beta = 0.5
		               	r.votes = 0
		               	r.save()                        

			return HttpResponseRedirect('/success/')
	else:
		form = ProductForm()
	return render_to_response(template_name, locals(), context_instance = RequestContext(request))
Exemple #57
0
def edit_product(request,id):
    product_instance=Product.objects.get(id=id)
    form=ProductForm(request.POST or None,instance=product_instance)
    if form.is_valid():
        form.save()
    return render_to_response("edit_product.html",locals(),context_instance=RequestContext(request))
def edit_product(request, id):
    product_instance = Product.objects.get(id = id)
    form = ProductForm(request.POST or None, instance = product_instance)
    if form.is_valid():
        form.save()
    return render(request, 'marketapp/edit_product.html', locals())
def create_product(request):
    form = ProductForm(request.POST or None)
    if form.is_valid():
        form.save()
        form = ProductForm()
    return render(request, 'marketapp/create_product.html', locals())