Beispiel #1
0
def add():

    form = ProductForm()

    if form.validate_on_submit():
        file_name = str(time_stamp()) + secure_filename(
            form.image.data.filename)
        img_path = join(UPLOAD_DIR, file_name)

        product = Product(name=form.name.data,
                          price=form.price.data,
                          stock=form.stock.data,
                          description=form.description.data,
                          image=file_name,
                          type=form.type.data,
                          live=True)

        db.session.add(product)
        db.session.commit()
        form.image.data.save(img_path)

        return if_url_is_safe_redirect(
            url_for('admin_app.admin'),
            route_func_name_to_redirect_to='admin_app.add')
    return render_template('admin/add-product.html', admin=True, form=form)
Beispiel #2
0
    def post(self, request, *args, **kwargs):
        """
        Create product if form is valid
            or return status code 400
            and form with suggest errors.
        """

        form = ProductForm(request.POST)
        if form.is_valid():
            form.save()
            return render(
                request,
                self.__class__.TABLE_TEMPLATE,
                {
                    "object_list":
                    Product.objects.select_related("provider").all().order_by(
                        "created_at")
                },
            )

        return render(
            request,
            self.__class__.FORM_TEMPLATE,
            {"form": form},
            status=400,
        )
Beispiel #3
0
def product_add(request):
    form = ProductForm(request.POST or None)
    if form.is_valid():
        form.save()
        return HttpResponseRedirect(reverse("product:product_list"))
    context = {"form": form}
    return render(request, "form.html", context)
Beispiel #4
0
def item(request, product_id):
    product = get_object_or_404(Product, id = product_id)
    form = ProductForm(instance = product, provider = product.provider)
    url_args = request.GET.urlencode()

    if request.method == 'POST':
        data = request.POST.copy()
        url_args = data.pop('url_args')
        form = ProductForm(instance = product, data = data)
        if form.is_valid():
            if form.has_changed():
                orig_price = product.price
                product = form.save()
                if orig_price != product.price and product.has_expired():
                    product.expiry = datetime.strptime("31/12/%s" % timezone.now().year, "%d/%m/%Y")
                    product.save()

                info_msg(request, u"Produit modifié avec succès.")
            return redirect(reverse('product:list') + '?' + url_args[0])

    product_type = ContentType.objects.get_for_model(Product)
    return render(request, 'product/item.html', {
        'product': product,
        'product_type': product_type.id,
        'form': form,
        'url_args': url_args
    })
Beispiel #5
0
 def post(self, request):
     form = ProductForm(data=request.POST, files=request.FILES)
     if form.is_valid():
         form.save()
         return redirect('/manager/')
     else:
         return HttpResponse("Sai cu phap")
Beispiel #6
0
    def post(self, request, *args, **kwargs):
        category = Category.objects.all().order_by('order')

        a = AuctionForm(data=request.POST)
        p = ProductForm(data=request.POST, files=request.FILES)

        images = dict(request.FILES)

        if a.is_valid() and p.is_valid():
            auction = a.save(commit=False)
            product = p.save(commit=False)
            auction.owner = request.user
            auction.last_bet = auction.start_price
            auction.next_bet = auction.last_bet + decimal.Decimal(auction.start_price / 100 * auction.increment)

            auction.save()
            product.auction = auction
            product.save()

            for i in images:
                ImageModel.objects.create(image=images[i][0], product=product)

            return redirect('profile')

        return render(request, self.template_name, context={
            "category": category,
            "auctionform": a,
            "productform": p,

        })
Beispiel #7
0
def update(request, id):
    product = Product.objects.get(id=id)
    form = ProductForm(request.POST, instance=product)
    if form.is_valid():
        form.save()
        return redirect("/show")
    return render(request, 'edit.html', {'product': product})
Beispiel #8
0
def createProduct(request):
    form = ProductForm(data=request.POST or None, files=request.FILES or None)
    if request.method == "POST":
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/list_edit/')

    return render(request, 'product_create.html', {'form': form})
Beispiel #9
0
def save_product(request):
    form = ProductForm(request.POST or None, request.FILES or None)
    if form.is_valid():
        product = form.save(commit=False)
        product.user = request.user
        product.save()
        return HttpResponseRedirect(reverse("product:product_list"))
    context = {"form": form}
    return render(request, "form.html", context)
Beispiel #10
0
def edit_product(request, id):
    product = get_object_or_404(Product, id=id)
    form = ProductForm(request.POST or None,
                       request.FILES or None,
                       instance=product)
    if form.is_valid():
        form.save()
        return HttpResponseRedirect(reverse("product:product_list"))
    context = {"form": form}
    return render(request, "form.html", context)
Beispiel #11
0
def add_product(request):
    form = ProductForm(data=request.POST or None, files=request.FILES or None)
    if request.method == "POST":
        if form.is_valid():
            product = form.save()
            messages.success(
                request, f"{product.title} is added successfully.")
            return redirect(product.get_absolute_url())

    context = {'form': form}
    return render(request, 'dashboard/add_product.html', context)
    def post(self, *args, **kwargs):
        context = {}

        form = ProductForm(self.request.POST, self.request.FILES)
        if form.is_valid():
            new_product = form.save()
            new_product.user = self.request.user
            new_product.save()
            context["products"] = Product.objects.filter(availability=True,
                                                         delete=False)
            context["message"] = "Товар добавлен"
            return render(self.request, "product/products.html", context)
Beispiel #13
0
 def post(self, request):
     """Save product and redirect to product list."""
     form = ProductForm(request.POST)
     if form.is_valid():
         new_product = form.save()
         return redirect('product:product_images_add',
                         product_id=new_product.id)
     else:
         return render(request, 'product/add-product.html', {
             'form': form,
             'func': 'Add'
         })
Beispiel #14
0
 def test_invalid_form(self):
     image = InMemoryUploadedFile(
         StringIO(TEST_IMAGE),
         field_name='image',
         name='1.JPG',
         content_type='image/jpg',
         size=len(TEST_IMAGE),
         charset='utf-8',
     )
     data ={'name':'','description':'descripcion','price':'100.00'}
     form = ProductForm(data=data, files={'image':image})
     self.assertFalse(form.is_valid())
Beispiel #15
0
def add_to_cart(request, product_id):
	products = Product.objects.all()
	product = get_object_or_404(products, pk=product_id)
	response = views.product(request, product.get_slug,  product_id)
	cart = get_or_create_cart(request)
	form = ProductForm(request.POST)
	if form.is_valid():
		quantity = form.cleaned_data['quantity']
		if not form.cleaned_data['quantity']:
			quantity = 1
		save_to_cart(cart, product, quantity)
	if not request.user.is_authenticated:
		set_cart_cookie(cart, response)
	return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
Beispiel #16
0
def add_view(request, *args, **kwargs):
    if request.method == 'POST':
        form = ProductForm(data=request.POST, files=request.FILES)
        if form.is_valid():
            form = form.save(commit=False)
            form.company = request.user.seller_set.all().first()
            form.save()
            return redirect('seller:products')
    else:
        form = ProductForm()
    return render(request, 'sellers/add_product.html', {'form': form})
Beispiel #17
0
def addProductsInLineForm(request,context):
    form1 = ProductForm(request.POST or None)
    # form1 = CategoryForm()
    # if form1.is_valid():
    #     instance = form1.save(commit=False)
    #     instance.save()

    form2 = TaxForm(request.POST or None)
    # form1 = CategoryForm()
    # if form2.is_valid():
    #     instance = form2.save(commit=False)
    #     instance.save()

    form3 = BrandForm(request.POST or None)
    # form1 = CategoryForm()
    # if form3.is_valid():
    #     instance = form3.save(commit=False)
    #     instance.save()

    form4 = TaxSlabForm(request.POST or None)
    # form1 = CategoryForm()
    # if form4.is_valid():
    #     instance = form4.save(commit=False)
    #     instance.save()

    context['form1'] = form1
    context['form2'] = form2
    context['form3'] = form3
    context['form4'] = form4
Beispiel #18
0
 def get(self, request):
     """Return add new product form."""
     form = ProductForm()
     return render(request, 'product/add-product.html', {
         'form': form,
         'func': 'Add'
     })
Beispiel #19
0
 def post(self, request, variant_id):
     if request.is_ajax():
         data = request.POST
         if 'is_product_edited' in data and data['is_product_edited']:
             if not self.request.user.has_perm('product.change_product'):
                 return JsonResponse(
                     {'permission_denied': 'Permission denied'},
                     status=400,
                     safe=False)
             form = ProductForm(data)
             if form.is_valid():
                 cleaned_data = form.cleaned_data
                 Product.objects.update_product(data['id'], cleaned_data)
                 return JsonResponse("success", status=201, safe=False)
             else:
                 return JsonResponse(form.errors, status=400)
         elif 'is_variant_edited' in data and data['is_variant_edited']:
             if not self.request.user.has_perm(
                     'product.change_productvariant'):
                 return JsonResponse(
                     {'permission_denied': 'Permission denied'},
                     status=400,
                     safe=False)
             form = VariantForm(data)
             if form.is_valid():
                 cleaned_data = form.cleaned_data
                 ProductVariant.objects.update_variant(
                     variant_id, cleaned_data)
                 return JsonResponse("success", status=201, safe=False)
             else:
                 return JsonResponse(form.errors, status=400)
         else:
             if not self.request.user.has_perm(
                     'product.change_product'
             ) and self.request.user.has_perm(
                     'product.change_productvariant'):
                 return JsonResponse(
                     {'permission_denied': 'Permission denied'},
                     status=400,
                     safe=False)
             form = NewStockForm(data)
             if form.is_valid():
                 cleaned_data = form.cleaned_data
                 supplier = ProductVariant.objects.add_new_stock(
                     id=variant_id, form_data=cleaned_data)
                 date = datetime.strftime(supplier.date,
                                          '%d/%m/%Y %I:%M %p')
                 return JsonResponse(
                     {
                         'date': date,
                         'name': cleaned_data['supplier'].name,
                         'mobile_no': cleaned_data['supplier'].mobile_no,
                         'total_supplied': supplier.total_supplied,
                         'per_product_purchase_price':
                         supplier.per_product_purchase_price,
                         'address': cleaned_data['supplier'].address
                     },
                     status=201)
             else:
                 return JsonResponse(form.errors, status=400)
Beispiel #20
0
def new(request):
    provider = None
    form = ProductForm()

    if request.method == 'GET':
        provider_id = request.GET.get('provider_id', None)
        if provider_id:
            provider = get_object_or_404(Provider, id = provider_id)
            form = ProductForm(provider = provider)
        elif request.user.has_perm("order.custom_view_local_provider"):
            provider = get_object_or_404(Provider, name = 'MAGASIN', is_local = True)
            form = ProductForm(provider = provider)
    elif request.method == 'POST':
        if 'provider' in request.POST and request.POST['provider']:
            provider = get_object_or_404(Provider, id = request.POST['provider'])
            form = ProductForm(provider = provider, data = request.POST)
        else:
            provider = None
            form = ProductForm(data = request.POST)

        if form.is_valid():
            p = form.save()
            if p.provider.reseller:
                p.origin = p.provider.name
                p.provider = p.provider.reseller
                p.save()

            info_msg(request, u"Produit ajouté avec succès.")
            return redirect(reverse('product:list') + "?reference=%s&connector=OR" % p.reference)

    return render(request, 'product/new.html', {
        'provider': provider,
        'form': form
    })
Beispiel #21
0
def item(request, product_id):
    product = get_object_or_404(Product, id=product_id)
    if request.method == 'GET':
        form = ProductForm(instance=product, provider=product.provider)
        url_args = request.GET.urlencode()
    elif request.method == 'POST':
        data = request.POST.copy()
        url_args = data.pop('url_args')
        form = ProductForm(instance=product, data=data)
        if form.is_valid():
            if form.has_changed():
                orig_price = product.price
                product = form.save()
                if orig_price != product.price and product.has_expired():
                    product.expiry = datetime("31/12/%s" % datetime.now().year,
                                              "%d/%m/%Y")
                    product.save()

                info_msg(request, u"Produit modifié avec succès.")
            return redirect(reverse('product_index') + '?' + url_args[0])

    product_type = ContentType.objects.get_for_model(Product)
    return render(
        request, 'product/item.html', {
            'product': product,
            'product_type': product_type.id,
            'form': form,
            'url_args': url_args
        })
Beispiel #22
0
def product_create(request):
    context = {}
    if request.method == "POST":
        form = ProductForm(request.POST,request.FILES)
        if form.is_valid():
            new_product = form.save()
            new_product.user = request.user
            new_product.save()
            context["products"] = Product.objects.filter(
                available=True,
                deleted=False
                )
            context["message"] = "Товар был успешно добавлен"
            return redirect(products)
    
    context["form"] = ProductForm

    return render(request,"product/form.html",context)
Beispiel #23
0
 def get(self, request, action_id):
     if action_id == 1:
         product = ProductForm()
         return render(request, "store/manage_Action.html",
                       {"add_product": product})
     if action_id == 2:
         category = CategoryForm()
         return render(request, "store/manage_Action.html",
                       {"add_category": category})
Beispiel #24
0
def product_creation_edit(request, product_id=None):
    """

    :param request:
    :param product_id:
    :return:
    """
    context = dict()
    if product_id:
        context['product_id'] = product_id
    query = get_object_or_404(Product, pk=product_id) if product_id else None
    form = ProductForm(request.POST or None, instance=query)
    if request.POST and form.is_valid():
        form.save()
        return redirect('product-list')
    else:
        context['form'] = form
    return render(request, 'product/product-creation-edit.html', context=context)
Beispiel #25
0
 def get(self, request, id):
     """Return Update new product form."""
     product = get_object_or_404(Product, id=id)
     form = ProductForm(instance=product)
     return render(request, 'product/add-product.html', {
         'form': form,
         'func': 'Update',
         'product': product
     })
Beispiel #26
0
def editProduct(request, id):
    product = get_object_or_404(Product, pk=id)

    product_form = ProductForm(instance=product)

    request.session['product_id'] = id

    return render(request, 'product/createProduct.html',
                  {'form': product_form})
Beispiel #27
0
def editProduct(request, product_id):
    product_info = None
    try:
        product_info = get_object_or_404(Product, pk=product_id)
    except:
        product_info = None

    form = ProductForm(data=request.POST or None,
                       files=request.FILES or None,
                       instance=product_info)
    # 주석처리 된 코드도 위의 코드와 동치입니다. (인자 순서에 따른 인자명 생략)
    # form = ProductForm(request.POST or None, request.FILES or None ,instance=product_info)

    if request.method == "POST":
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/list_edit/')

    return render(request, 'product_edit.html', {'form': form})
Beispiel #28
0
 def post(self, request, id):
     """Update product and redirect to product list."""
     product = get_object_or_404(Product, id=id)
     form = ProductForm(request.POST, instance=product)
     has_images = ProductImages.objects.filter(product=product).exists()
     if form.is_valid():
         new_product = form.save()
         if has_images:
             return redirect('product:product_images_update',
                             product_id=new_product.id)
         else:
             return redirect('product:product_images_add',
                             product_id=new_product.id)
     else:
         return render(request, 'product/add-product.html', {
             'form': form,
             'func': 'Update',
             'product': product
         })
Beispiel #29
0
    def post(self, request, *args, **kwargs):
        id = kwargs['id']
        category = Category.objects.all().order_by('order')

        auction = Auction.objects.get(pk=id)
        a = AuctionForm(instance=auction, data=request.POST)
        p = ProductForm(instance=auction.lot, data=request.POST, files=request.FILES)

        if a.is_valid() and p.is_valid():
            a.save()
            p.save()
            return redirect('profile')

        return render(request, self.template_name, context={
            "category": category,
            "auctionform": a,
            "productform": p,
            "auction": auction,

        })
Beispiel #30
0
    def get(self, request, *args, **kwargs):
        """
        Return empty rendered form, without error suggest.
        """

        return render(
            request,
            self.__class__.FORM_TEMPLATE,
            {"form": ProductForm()},
            status=200,
        )
Beispiel #31
0
def add_product(request):
	user = request.user
	merchant = Merchant.objects.get(user=user)
	if request.method == 'POST':
		form = ProductForm(request.POST, request.FILES)
		if form.is_valid():
			product = Product(merchant=merchant,name=form.cleaned_data['name'],
							  category=form.cleaned_data['category'],
							  selling_price=form.cleaned_data['selling_price'],
							  original_price=form.cleaned_data['original_price'],
							  quantity=form.cleaned_data['quantity'],
							  photo = request.FILES['photo'])
			product.save()
			return HttpResponseRedirect('/merchant')

		else:
			pass
	else:
		form = ProductForm()
	variables = RequestContext(request, {'form': form})
	return render_to_response('product/add_product.html', variables)
Beispiel #32
0
def add(request):
    if request.method == 'POST':
        form = ProductForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/')
    else:
        form = ProductForm()

    return render(request, 'product/form.html', {'form': form})
Beispiel #33
0
    def get(self, request, *args, **kwargs):
        category = Category.objects.all().order_by('order')

        a = AuctionForm()
        p = ProductForm()

        return render(request, self.template_name, context={
            "category": category,
            "auctionform": a,
            "productform": p,

        })
Beispiel #34
0
def deleteproduct(request, pk):
    msg = ""
    product = Product.objects.get(id=pk)
    if request.method == "POST":
        product.delete()
        return redirect("/")
    else:
        form = ProductForm(instance=product)
    return render(request, "product/check_product.html", {
        "form": form,
        "message": msg
    })
Beispiel #35
0
def product_create(request, collection_id):
    collection = Collection.objects.get(id=collection_id)
    ChildProductFormSet = modelformset_factory(Product, form=ChildProductForm)
    if request.method == 'POST':
        product_form = ProductForm(request.POST)
        child_formset = ChildProductFormSet(request.POST, prefix='child')
        if product_form.data.has_key('has_options'):
            if child_formset.is_valid() and product_form.is_valid():
                check = True
            else:
                check = False
        else:
            if product_form.is_valid():
                check = True
            else:
                check = False
        if check:
            product = product_form.save(commit=False)
            product.collection = collection 
            product.category = collection.category
            product.brand = collection.brand
            product.save()
            product_form.save_m2m()

            if product.has_options:
                for (counter, form) in enumerate(child_formset.forms):
                    child = form.save(commit=False) 
                    child.parent = product
                    child.name = product.name
                    child.description = product.description
                    child.brand = product.brand
                    child.category = product.category
                    child.has_options = True
                    child.option_group = product.option_group
                    if not child.price:
                        child.price = product.price
                    child.collection = collection
                    child.slug = product.slug + '-' + child.option.name
                    child.save()
                    for gender in product.gender.all():
                        child.gender.add(gender)
            if 'add' in request.POST:   
                return redirect('staff-product-image', product.id)
            else:
                return redirect('staff-collection', collection_id=collection_id)
    else:
        product_form = ProductForm()
        child_formset = ChildProductFormSet(prefix='child', queryset=Product.objects.none())

    return render(request, 'staff/create-product.html', {
        'collection': collection,
        'product_form': product_form,
        'child_formset': child_formset,
    })
Beispiel #36
0
def product_edit(request, collection_id, product_id):
    from django.http import HttpResponse
    product = get_object_or_404(Product, id=product_id)
    collection = Collection.objects.get(id=collection_id)
    children = Product.objects.filter(parent=product)
    if children:
        ChildProductFormSet = modelformset_factory(Product, form=ChildProductForm, extra=0)
    else:
        ChildProductFormSet = modelformset_factory(Product, form=ChildProductForm)

    product_form = ProductForm(request.POST or None, instance=product)
    if request.method == 'POST':
        child_formset = ChildProductFormSet(request.POST, prefix='child')

        if product_form.data.has_key('has_options'):
            if child_formset.is_valid() and product_form.is_valid():
                check = True
            else:
                check = False
        else:
            if product_form.is_valid():
                check = True
            else:
                check = False

        if check:
            product = product_form.save()
            if product.has_options:
                for (counter, form) in enumerate(child_formset.forms):
                    child = form.save(commit=False)
                    child.parent = product
                    child.name = product.name
                    child.description = product.description
                    child.brand = product.brand
                    child.category = product.category
                    child.has_options = True
                    child.option_group = product.option_group
                    if not child.price:
                        child.price = product.price
                    child.collection = collection
                    child.slug = product.slug + '-' + child.option.name
                    child.save()
                    child.gender.clear()
                    for gender in product.gender.all():
                        child.gender.add(gender)

                    children = children.exclude(id=child.id)

                children.delete()

            if 'add' in request.POST:   
                return redirect('staff-product-image', product.id)
            else:
                return redirect('staff-collection', collection_id)

    child_formset = ChildProductFormSet(prefix='child', queryset=children)

    return render(request, 'staff/edit-product.html', {
        'collection': collection,
        'product_form': product_form,
        'child_formset': child_formset,
    })