NotesWhat is notes.io?

Notes brand slogan

Notes - notes.io

models.py

from django.db import models

# Create your models here.

class Product(models.Model):
name = models.CharField(max_length=100)
category = models.CharField(max_length=50)
price = models.DecimalField(max_digits=10, decimal_places=2)
quantity = models.IntegerField()
discount = models.IntegerField()
barcode = models.CharField(max_length=50,unique=True)


urls.py main

"""inventoryapi URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Add an import: from blog import urls as blog_urls
2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
"""
from django.urls import include,re_path as url
from django.urls import path
from django.contrib import admin
from rest_framework.routers import DefaultRouter

#Add your URLS in respective place.


urlpatterns = [
url(r'^admin/',admin.site.urls),
path('', include('inventoryapp.urls'))
]



urls.py project

from django.urls import include,re_path as url
from django.urls import path

from .views import add_item, delete_item, get_items_by_category, get_sorted_items,showHello

urlpatterns = [
path('',showHello, name='showHello'),
path('inventory/items/', add_item, name='add_item'),
path('inventory/items/<int:id>/', delete_item, name='delete_item'),
path('items/query/<str:category>/', get_items_by_category, name='get_items_by_category'),
path('items/sort/', get_sorted_items, name='get_sorted_items'),
]

views.py

from django.http import JsonResponse,HttpResponse
from django.views.decorators.csrf import csrf_exempt
from .models import Product
from .serializer import ProductSerializer1
import json,traceback
import requests

@csrf_exempt
def showHello(request):
res = requests.post('http://127.0.0.1:8000/inventory/items/',data={'name':'shirt','category':'top wear','price':700,'discount':20,'quantity':2,'barcode':123456})
res1 = requests.post('http://127.0.0.1:8000/inventory/items/',data={'name':'t-shirt','category':'top wear','price':1300,'discount':30,'quantity':2,'barcode':12345687})
# res = requests.post('{'name':'shorts','category':'bottom wear','price':300,'discount':5,'quantity':3,'barcode':123455}')
resp2 = requests.get('http://127.0.0.1:8000/items/query/top%20wear/')
print(resp2.json())
# print(b'inventory with this barcode already exists' in res1.content)
# print('res', res.content)
return HttpResponse("Hello, World!")

@csrf_exempt
def add_item(request):
try:
if request.method == 'POST':
# data = json.loads(request.body)
data = request.POST
serializer = ProductSerializer1(data=data)
print(serializer.is_valid())
if serializer.is_valid():
# Extract barcode from the validated data
barcode = data['barcode']
print(barcode)
# Check if product with the same barcode already exists
if Product.objects.filter(barcode=barcode).exists():
print("inventory with this barcode already exists")
return JsonResponse({"error": "inventory with this barcode already exists"}, status=400)

# Save the product if it doesn't already exist
serializer.save()
return JsonResponse(serializer.data, status=201)
else:
barcode = data['barcode']
print(barcode)
# Check if product with the same barcode already exists
if Product.objects.filter(barcode=barcode).exists():
print("inventory with this barcode already exists")
return JsonResponse({"error": "inventory with this barcode already exists"}, status=400)
print(serializer.errors)
return JsonResponse(serializer.errors, status=400)

if request.method == 'GET':
products = Product.objects.all()
serializer = ProductSerializer1(products, many=True)
return JsonResponse(serializer.data, safe=False, status=200)
except Exception as e:
print(traceback.format_exc())
return JsonResponse({"error": str(e)}, status=500)

@csrf_exempt
def delete_item(request, id):
print(request)
if request.method == 'DELETE':
try:
print(26, request)
product = Product.objects.get(id=id)
product.delete()
return JsonResponse({}, status=204)
except Product.DoesNotExist:
print(traceback.format_exc())
return JsonResponse({{"error": "Item not found"}}, status=404)
except Exception as e:
print(traceback.format_exc())
return JsonResponse({"error": str(e)}, status=500)

if request.method == 'PUT':
try:
product = Product.objects.get(id=id)
# data = json.loads(request.body)
data = request.POST
serializer = ProductSerializer1(product, data=data)
if serializer.is_valid():
serializer.save()
return JsonResponse(serializer.data, status=200)
return JsonResponse(serializer.errors, status=400)
except Product.DoesNotExist:
return JsonResponse({}, status=400)
else:
return JsonResponse({"error": "Method not allowed"}, status=405)

# def get_all_items(request):
# if request.method == 'GET':
# products = Product.objects.all()
# serializer = ProductSerializer1(products, many=True)
# return JsonResponse(serializer.data, safe=False, status=200)

def get_items_by_category(request, category):
try:
if request.method == 'GET':
products = Product.objects.filter(category=category)
serializer = ProductSerializer1(products, many=True)
return JsonResponse(serializer.data, safe=False, status=200)
except Exception as e:
print(traceback.format_exc())
return JsonResponse({"error": str(e)}, status=500)
def get_sorted_items(request):
if request.method == 'GET':
products = Product.objects.order_by('-price')
serializer = ProductSerializer1(products, many=True)
return JsonResponse(serializer.data, safe=False, status=200)
import requests

def test(request):
res = requests.post('/inventory/items/',data={'name':'shirt','category':'top wear','price':700,'discount':20,'quantity':2,'barcode':123456})
print(res.json())


seee.py

from rest_framework import serializers
from .models import Product

#Create your serializers here.
class ProductSerializer1(serializers.ModelSerializer):
price = serializers.FloatField()
quantity = serializers.IntegerField()
barcode = serializers.CharField()

class Meta:
model = Product
fields = ['id', 'name', 'category', 'price', 'quantity', 'barcode','discount']




     
 
what is notes.io
 

Notes.io is a web-based application for taking notes. You can take your notes and share with others people. If you like taking long notes, notes.io is designed for you. To date, over 8,000,000,000 notes created and continuing...

With notes.io;

  • * You can take a note from anywhere and any device with internet connection.
  • * You can share the notes in social platforms (YouTube, Facebook, Twitter, instagram etc.).
  • * You can quickly share your contents without website, blog and e-mail.
  • * You don't need to create any Account to share a note. As you wish you can use quick, easy and best shortened notes with sms, websites, e-mail, or messaging services (WhatsApp, iMessage, Telegram, Signal).
  • * Notes.io has fabulous infrastructure design for a short link and allows you to share the note as an easy and understandable link.

Fast: Notes.io is built for speed and performance. You can take a notes quickly and browse your archive.

Easy: Notes.io doesn’t require installation. Just write and share note!

Short: Notes.io’s url just 8 character. You’ll get shorten link of your note when you want to share. (Ex: notes.io/q )

Free: Notes.io works for 12 years and has been free since the day it was started.


You immediately create your first note and start sharing with the ones you wish. If you want to contact us, you can use the following communication channels;


Email: [email protected]

Twitter: http://twitter.com/notesio

Instagram: http://instagram.com/notes.io

Facebook: http://facebook.com/notesio



Regards;
Notes.io Team

     
 
Shortened Note Link
 
 
Looding Image
 
     
 
Long File
 
 

For written notes was greater than 18KB Unable to shorten.

To be smaller than 18KB, please organize your notes, or sign in.