def VersionProduct(request, pk): # dictionary for initial data with # field names as keys context = {} # fetch the object related to passed id obj = get_object_or_404(Product, pk=pk) #obj.photo.delete() #obj.photo.open(mode='rb') # pass the object as instance in form form = ProductForm(request.POST or None, instance=obj) # save the data from the form and # redirect to detail_view if form.is_valid(): obj.pk = int(round(time.time() * 1000)) #form.photo = request.POST.get('photo', False) #form.photo = request.FILES['photo'] form.instance.creator = request.user form.save() return HttpResponseRedirect(reverse("products:all")) else: # add form dictionary to context context["form"] = form return render(request, "products/product_form.html", context)
def addProduct(request): ImageFormset = modelformset_factory(ImageModelProduct, form=ImageForm, extra=4) prod_form = ProductForm(request.POST) if request.method == 'POST': formset = ImageFormset(request.POST or None, request.FILES, queryset=ImageModelProduct.objects.none()) if formset.is_valid() and prod_form.is_valid(): imageNull_count = 0 for form in formset.cleaned_data: if form == {}: imageNull_count += 1 if imageNull_count == 4: return JsonResponse( {'error': "need to upload at least 1 photo"}, status=200) product = prod_form.save() print(formset.cleaned_data) for form in formset.cleaned_data: print(form) if form: image = form['image'] photo = ImageModelProduct(product=product, image=image) photo.save() return JsonResponse({'product': product.title}, status=200) else: return JsonResponse({'product_error': prod_form.errors.as_json()}, status=200) return redirect('adminView') return render(request, 'admin_unnies/adminDashboard.html', {})
def edit_product(request, product_id): product = Product.objects.get(id=product_id) product_form = ProductForm(request.POST or None, instance=product) if request.method == 'POST': if product_form.is_valid(): product = product_form.save() all_images = product.productimage_set.all().delete() if product_form.cleaned_data.get('image_1'): ProductImage.objects.create( product=product, url=product_form.cleaned_data.get('image_1')) if product_form.cleaned_data.get('image_2'): ProductImage.objects.create( product=product, url=product_form.cleaned_data.get('image_2')) if product_form.cleaned_data.get('image_3'): ProductImage.objects.create( product=product, url=product_form.cleaned_data.get('image_3')) return redirect('products') return render(request, 'edit_product.html', { 'product': product, 'product_form': product_form })
def add_product(request): if not request.user.is_authenticated: print('dhukse') msg = "Please Login or Register" messages.add_message(request, messages.ERROR, msg) return HttpResponseRedirect(request.META.get('HTTP_REFERER')) elif request.method == 'POST': product_form = ProductForm(request.POST, request.FILES) if product_form.is_valid(): new_product = product_form.save(commit=False) new_product.owner = request.user new_product.save() msg = "Product has been added" messages.add_message(request, messages.SUCCESS, msg) else: msg = "Adding Product Failed" messages.add_message(request, messages.ERROR, msg) """ @send user greetings """ return HttpResponseRedirect(request.META.get('HTTP_REFERER')) else: form = ProductForm() return render(request, 'addproduct.html', { 'category_list': cattag, 'form': form, 'title': 'Add Product Form' })
def saveProduct(request): if request.method == 'POST' and request.user.is_authenticated(): productForm = ProductForm(request.POST, prefix='product') if productForm.is_valid(): category_form = CategoryForm(data=request.POST, prefix='category') if category_form.is_valid(): producto = saveProductData(request, productForm) imageForm = ImagesForm(request.POST, request.FILES, prefix='image') if imageForm.is_valid(): producto.save() saveCategoryData(producto, category_form) saveAlbumData(producto, request.user.id) saveImages(request, producto.img) puntos = Point.objects.get(action="new_product") profile = request.user.profile profile.quds = profile.quds + int(puntos.qty) profile.save() else: return HttpResponse("NO FILES") return HttpResponseRedirect("/products/" + str(producto.id)) else: return HttpResponse("CATEGORY FAIL") else: return HttpResponse("INVALID PRODUCT") return HttpResponse("FAIL")
def saveProduct(request): if request.method == 'POST' and request.user.is_authenticated(): productForm = ProductForm(request.POST, prefix='product') if productForm.is_valid(): category_form = CategoryForm(data=request.POST, prefix='category') if category_form.is_valid(): producto = saveProductData(request, productForm) imageForm = ImagesForm(request.POST,request.FILES, prefix='image') if imageForm.is_valid(): producto.save() saveCategoryData(producto, category_form) saveAlbumData(producto, request.user.id) saveImages(request, producto.img) puntos = Point.objects.get(action="new_product") profile = request.user.profile profile.quds = profile.quds + int(puntos.qty) profile.save() else: return HttpResponse("NO FILES") return HttpResponseRedirect("/products/" + str(producto.id)) else: return HttpResponse("CATEGORY FAIL") else: return HttpResponse("INVALID PRODUCT") return HttpResponse("FAIL")
def post(self, request): success_message = '' product_with_owner = Product() product_with_owner.owner = request.user form = ProductForm(request.POST, request.FILES, instance=product_with_owner) if form.is_valid(): form.save() success_message = '¡Producto publicado con éxito!' context = { 'form_category': form.data['category'], 'form_description': form.data['description'], 'form_functionality': form.data['functionality'], 'form_image': format_html( '<img src=/media/{}/{} width="230" height="200"/>'.format( request.user, request.FILES['image'])), 'form_location': form.data['location'], 'success_message': success_message, } return render(request, 'products/newProductOk.html', context)
def product_form(request): form = ProductForm(request.POST) if form.is_valid(): form.save() Product.objects.create(**form.cleaned_data) print(form) context = {'form': form} return render(request, "test3.html", context)
def post(self, request, *args, **kwargs): """Process the post request with a new Product form filled out.""" form = ProductForm(request.POST) if form.is_valid(): product_obj = form.save(commit=True) return HttpResponseRedirect('/products/detail/' + str(product_obj.id)) return render(request, "product/product_create.html", {'form': form})
def create_product(request): form = ProductForm(request.POST or None) if form.is_valid(): form.save() return redirect('list_products') return render(request, 'products-form.html', {'form': form})
def create_product(request): form = ProductForm(request.POST or None) if form.is_valid(): form.save() context = {'form': form} return render(request, 'products/create_product.html', context=context)
def product_create(request): form = ProductForm(request.POST or None) if request.method == "POST": if form.is_valid(): form.save() return redirect('products:products') return render(request, "products/product_create.html", context={"form": form})
def update_product(request, id): product = Product.objects.get(id=id) form = ProductForm(request.POST or None, instance=product) if form.is_valid(): form.save() return redirect('list_products') return render(request, 'products-form.html', {'form': form, 'product': product})
def AddProducts(request): data = { 'form': ProductForm } if request.method == 'POST': form_add_product = ProductForm(data=request.POST) form_add_product.save() messages.success(request, 'El producto se ha guardado exitosamente') return redirect(to='Products') return render(request, 'products/addProducts.html', data)
def test_sku_is_not_required(self): form = ProductForm({ 'name': 'Test Name' 'description:' 'Test Description' 'price:' '£9.99' }) self.assertFalse(form.is_valid())
def add_product(request, product_id=None): product = Product.objects.get(product_id=product_id) if request.method == "POST": productform = ProductForm(request.POST, instance=product) if productform.is_valid(): product = productform.save() return HttpResponseRedirect(product.get_absolute_url()) else: productform = ProductForm(instance=product) return render(request, "add_product.html", {"form": productform})
def editar(request, id): product = Product.objects.get(id=id) form = ProductForm(request.POST, instance=product) if form.is_valid(): form.save() return redirect('/listar') #else: return render(request, 'editar.html', {'product': product})
def update(request, id): product = Product.objects.get(id=id) form = ProductForm(request.POST, instance=product) if form.is_valid(): form.save() return redirect("../../products/show") else: # Added else statment msg = 'Errors: %s' % form.errors.as_text() return HttpResponse(msg, status=400)
def test_product_form_data_invalid(self): self.form = ProductForm( data={ 'category': self.test_category, 'name': "test_name1", 'description': "test description", 'size': "70cl", 'proof': 40, }) self.assertFalse(self.form.is_valid())
def create_product(request): if request.method != "POST": return HttpResponseNotAllowed(["POST"]) product_data = json.loads(request.body) form = ProductForm(product_data) if form.is_valid(): saved = form.save() return JsonResponse({"status": "Created", "id": saved.pk}, status=201) else: return JsonResponse(form.errors, status=400)
def edit_product(request, id): product = Product.objects.get(id=id) context = {'product': product, 'action': 'Editar'} if request.method == 'POST': product = ProductForm(request.POST, instance=product) if product.is_valid(): product.save() return redirect('user:home') else: print(product.errors) context['form'] = product return render(request, 'products/create_edit_product.html', context)
def create_product(request): print('POST:', request.POST) print('FILES:', request.FILES) context = {} if request.method == 'POST': product = ProductForm(request.POST, request.FILES) if product.is_valid(): product.save() return redirect('user:home') else: print(product.errors) context['form'] = product return render(request, 'products/create_edit_product.html', context)
def viewCreate(request): if request.POST: form = ProductForm(request.POST, request.FILES) if form.is_valid(): form.save() return HttpResponseRedirect('/home/') else: form = ProductForm() c = {} c.update(csrf(request)) c['form'] = form return render_to_response('createproduct.html', context_instance=RequestContext(request, c))
def product_update(request, pk): product = get_object_or_404(Product, pk=pk) form = ProductForm(request.POST or None, instance=product) if request.method == "POST": if form.is_valid(): form.save() messages.success(request, "Sucesso!") return redirect( reverse('products:product_update', kwargs={"pk": pk})) return render(request, "products/product_update.html", context={ "form": form, "product": product })
def product_edit(request, *args, **kwargs): # Initial data is used when you want a form input to have a default value # # initial_data = { # "price": 10 # } # form = ProductForm(request.POST or None,initial=initial_data) product = Product.objects.get(id=1) form = ProductForm(request.POST or None, instance=product) if form.is_valid(): form.save() context = {"form": form} return render(request, 'product/edit.html', context)
def add(request): if request.POST: form = ProductForm(request.POST) if form.is_valid(): form.save() # If the save was successful, redirect to another page redirect_url = reverse('products:list') return HttpResponseRedirect(redirect_url) else: form = ProductForm() content = {'title': 'Add new product', 'form': form} context_instance = RequestContext(request) return render_to_response('products/form.html', content, context_instance)
def edit_product(request, pk): product = Product.objects.get(pk=pk) if request.method == "GET": context = { 'product': product, 'form': ProductForm(instance=product), } return render(request, 'products/edit_product.html', context) else: form = ProductForm(request.POST, request.FILES, instance=product) if form.is_valid(): product.save() return redirect('user profile') context = {'form': form} return render(request, 'products/edit_product.html', context)
def product_list_view(request: HttpRequest) -> HttpResponse: """ Endpoint for listing, searching and creating Products. """ # Handling the Product creation form. form: ProductForm = ProductForm(request.POST or None) if request.method == "POST": if form.is_valid(): form.save() return redirect(reverse("products.list")) # Listing all Products. products: QuerySet = Product.objects.all() # Filtering by Product status. status: str = request.GET.get('status', '') if status: products = products.filter(status=status) # Filtering by product Name. name: str = request.GET.get('name', '') if name: products = products.filter(name__icontains=name) # Pagination. size: int = int(request.GET.get('size', 10)) offset: int = int(request.GET.get('offset', 1)) paginator: Paginator = Paginator(products, size) page: Page = paginator.page(offset) # Rendering Product list. return render(request, "products.html", { 'form': form, 'offset': offset, 'size': size, 'page': page, 'Status': Status, 'status': status, 'name': name, })
def viewUpdate(request, pk): id = pk if request.POST: products.objects.filter(id=id).delete() form = ProductForm(request.POST, request.FILES) if form.is_valid(): form.save() return HttpResponseRedirect('/home/') else: form = ProductForm() c = {} c.update(csrf(request)) c['id'] = id c['form'] = form return render_to_response('update.html', context_instance=RequestContext(request, c))
def add_product(request): form = ProductForm() form_post = ProductForm(request.POST) status = "none" return_string = 'products/add-product.html' if form_post.is_valid(): status = "pass" profile = form_post.save(commit=False) profile.user = request.user profile.active = True profile.save() products = Product.objects.all() context = {'products': products, 'product_form': form, "status": status} return render(request, return_string, context)
def forms(request): if request.POST: fileObj = request.FILES['image_url'] file_name = u"{0}_{1}.jpg".format(slugify(fileObj.name), generateGUID()) path = default_storage.save('product_images/' + file_name, ContentFile(fileObj.read())) print request.POST['looks'] product = Product.objects.create(name=request.POST['name']) product.description = request.POST['description'] product.price = request.POST['price'] product.price_unit = request.POST['price_unit'] product.link = request.POST['link'] product.primary_image_url = file_name product.save() return HttpResponseRedirect('/') else: form = ProductForm() data = {} data.update(csrf(request)) data['form'] = form return render( request, 'product_form.html', data, )
def get(self, request, *args, **kwargs): """Return a view with an empty form for creating a new Product.""" project_id = request.GET.get('project_id', ) project = Project.objects.get(id=project_id) form = ProductForm({'project': project}) ctx = {'form': form, 'project_id': project_id} return render(request, "product/product_create.html", ctx)
def product_create(request): if not request.user.is_staff or not request.user.is_superuser: raise Http404 form = ProductForm(request.POST or None, request.FILES or None) if form.is_valid(): instance = form.save(commit=False) instance.user = request.user instance.save() # message success messages.success(request, "Successfully Created") return HttpResponseRedirect(instance.get_absolute_url()) context = { "form": form, } return render(request, "products/product_form.html", context)
def test_product_crete_new(self): products = Product.objects.all() self.assertEqual(len(products), 1) self.assertEqual(Product.objects.count(), 1) new_product = { 'main-name': 'Novo produto', 'main-description': 'Produto simples de testes', 'main-price': 5.20, 'main-category': self.category_sucos.pk, 'product-TOTAL_FORMS': 2, 'product-INITIAL_FORMS': 0, 'product-MIN_NUM_FORMS': 0, 'product-MAX_NUM_FORMS': 1000, 'product-0-variation': self.broto_variation.pk, 'product-0-price': 10, 'product-1-variation': self.grande_variation.pk, 'product-1-price': 20, } product_form = Product() variations_formset = inlineformset_factory(Product, ProductVariation, form=ProductVariationForm, extra=1) form = ProductForm(new_product, instance=product_form, prefix='main') formset = variations_formset(new_product, instance=product_form, prefix='product') request = self.factory.post(reverse('product_new'), data=new_product) request.user = self.staff_user setattr(request, 'session', 'session') messages = FallbackStorage(request) setattr(request, '_messages', messages) self.assertEqual(form.is_valid(), True) self.assertEqual(formset.is_valid(), True) response = product_new(request) self.assertEqual(response.status_code, 302) self.assertEqual(response.url, '/products/list/') products = Product.objects.all() self.assertEqual(len(products), 2) self.assertEqual(Product.objects.count(), 2)
class TestForms(TestCase): def setUp(self): self.client = Client() self.test_category = Category.objects.create( pk=1, name="test_name", friendly_name="Test Name", ) self.test_product = Product.objects.create( pk=1, category=self.test_category, name="test_name1", description="test description", size="70cl", proof=40, price=25.50, ) def test_product_form_data_valid(self): self.form = ProductForm( data={ 'category': self.test_category, 'name': "test_name1", 'description': "test description", 'size': "70cl", 'proof': 40, 'price': 25.50, }) self.assertTrue(self.form.is_valid()) self.assertTrue( self.form.fields['category'].widget.attrs['placeholder'], "Category") self.assertTrue(self.form.fields['name'].widget.attrs['class'], 'user-profile-input') def test_product_form_data_invalid(self): self.form = ProductForm( data={ 'category': self.test_category, 'name': "test_name1", 'description': "test description", 'size': "70cl", 'proof': 40, }) self.assertFalse(self.form.is_valid())
def home(request): recents = Product.objects.filter(image_url__isnull=False).order_by('-created')[:6] term = None if request.method == 'POST': productform = ProductForm(request.POST) if productform.is_valid(): code = productform.cleaned_data['ASIN'] asin = re.compile("^B\d{2}\w{7}|\d{9}(X|\d)$") if asin.match(code): product = amazon_utils.get_or_create_product(code) else: asin, term = amazon_utils.random_product(code) while not asin and not term: time.sleep(1.5) asin, term = amazon_utils.random_product() product = amazon_utils.get_or_create_product(asin) ean = product.generate_barcode(type='ean13') upc = product.generate_barcode(type='upca') qrcode = product.generate_barcode(type='qrcode', text=False) return render_to_response('labels/generator_output.html', { 'product': product, 'ean': ean, 'upc': upc, 'qrcode': qrcode, 'search_term': term, }, context_instance=RequestContext(request)) else: productform = ProductForm() return render_to_response('labels/home.html', { 'product_form': productform, 'recents': recents, }, context_instance = RequestContext(request))
def add_or_edit(request, id=None): if id: product = get_object_or_404(Product, pk=id) action = "Edit " else: product = Product() action = "Add a new " if request.POST: form = ProductForm(request.POST, instance=product) if form.is_valid(): form.save() # If the save was successful, redirect to another page redirect_url = reverse('products:list') return HttpResponseRedirect(redirect_url) else: form = ProductForm(instance=product) content = {'title': action + 'product', 'form': form} context_instance = RequestContext(request) return render_to_response('products/form.html', content, context_instance)
def ManageCatalogView(request, shopid): if not request.user.groups.filter(name='shopadmin'): return HttpResponse("invalid group") template_name = "shops/manageCatalog.html" context = {} #check shop access perms try: shop = Shop.objects.get(id = shopid) if not shop.shop_admin.id == request.user.id: raise Exception except: return HttpResponse("The requested shop does not exist or is inaccessible for this current shopadmin.") product_form = None catalog_form = None context["shop"] = shop if request.method == 'POST': if request.GET.get("catalog_form") and int(request.GET.get("catalog_form")) == 2: #submitted print "catalog form submitted" catalog_form = ShopAdminCatalogForm(data=request.POST) if catalog_form.is_valid(): catalog_item = catalog_form.save(commit = False) catalog_item.shop = shop catalog_item.save() print "catalog item saved" catalog_form = None elif request.GET.get("product_form") and int(request.GET.get("product_form")) == 2: #submitted print "product form submitted" product_form = ProductForm(data=request.POST) if product_form.is_valid(): product_form.save() print "new product saved" product_form = None else: catalog_item_id_delete = request.GET.get("del") display_catalog_form = (request.GET.get("catalog_form")) display_product_form = (request.GET.get("product_form")) if catalog_item_id_delete: catalog_item = Catalog.objects.filter(id = catalog_item_id_delete) catalog_item.delete() if display_catalog_form: if int(display_catalog_form) == 1: catalog_form = ShopAdminCatalogForm() if display_product_form: if int(display_product_form) == 1: product_form = ProductForm() print catalog_item_id_delete print display_catalog_form print display_product_form context['catalog_form'] = catalog_form context['product_form'] = product_form #get list of shops owned catalog = shop.catalog_set.all() context['catalog'] = catalog #get list of shops owned shops = request.user.shop_set.all() context['shops'] = shops #shop ID part if shopid == None: shops = request.user.shop_set.all() if shops: shop = shops[0] else: shop = None #test that perms for specified shop exists else: try: shop = Shop.objects.get(id = shopid) if not shop.shop_admin.id == request.user.id: raise Exception except: return HttpResponse("The requested shop does not exist or is inaccessible for this current shopadmin.") context["shop"] = shop return render_to_response(template_name, context, context_instance=RequestContext(request))