def post(self, request): # print(request.body) # it will return binary string data = request.body json_data = json.loads(data) pf = ProductForm(json_data) if pf.is_valid(): pf.save() response = json.dumps({"success": "Product is saved"}) else: response = json.dumps(pf.errors) return HttpResponse(response, content_type="application/json")
def put(self, request, product): try: old_product = ProductModel.objects.get(no=product) new_product = json.loads(request.body) pf = ProductForm(new_product, instance=old_product) if pf.is_valid(): pf.save() json_data = json.dumps({"success": "Product is updated"}) else: json_data = json.dumps(pf.errors) return HttpResponse(json_data, content_type="application/json") except ProductModel.DoesNotExist: json_data = json.dumps({"error": "Invalid Product No"}) return HttpResponse(json_data, content_type="application/json")
def put(self, request, product): try: old_product = ProductModel.objects.get(no=product) new_product = json.loads(request.body) """ new data { "no": 5001, "name": "iphone6s", "price": 12000 "quantity": 200 } old_data { "no": 5001, "name": "iphone6s", "price": 2000 "quantity": 20 } """ data = { "no": old_product.no, "name": old_product.name, "price": old_product.price, "quantity": old_product.quantity } for key, value in new_product.items(): data[key] = value pf = ProductForm(data, instance=old_product) if pf.is_valid(): pf.save() json_data = json.dumps({"success": "Product is updated"}) else: json_data = json.dumps(pf.errors) return HttpResponse(json_data, content_type="application/json") except ProductModel.DoesNotExist: json_data = json.dumps({"error": "Invalid Product No"}) return HttpResponse(json_data, content_type="application/json")
def product_service_update(request, pk): product = get_object_or_404(TechnicalSolutions, pk=pk) product_form = ProductForm(instance=product) product_formset = inlineformset_factory(TechnicalSolutions, TechnicalSolutionsHasService, form=TechSolHasServiceForm, extra=1) formset = product_formset(instance=product) if request.method == 'POST': product_form = ProductForm(request.POST, instance=product) formset = product_formset(request.POST) if product_form.is_valid(): updated_product = product_form.save(commit=False) formset = product_formset(request.POST, instance=updated_product) if formset.is_valid(): updated_product.save() formset.save() return HttpResponseRedirect(updated_product.get_absolute_url()) context = { 'product_form': product_form, 'formset': formset, 'product': product, 'page_title': 'Обновление технических решений', 'bred_title': 'Обновление техрешений', } return render(request, 'productsapp/product_update.html', context)