diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..d75edeae --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +venv +__pycache__ \ No newline at end of file diff --git a/brand/__init__.py b/brand/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/brand/admin.py b/brand/admin.py new file mode 100644 index 00000000..8c38f3f3 --- /dev/null +++ b/brand/admin.py @@ -0,0 +1,3 @@ +from django.contrib import admin + +# Register your models here. diff --git a/brand/apps.py b/brand/apps.py new file mode 100644 index 00000000..cb0a8d86 --- /dev/null +++ b/brand/apps.py @@ -0,0 +1,6 @@ +from django.apps import AppConfig + + +class BrandConfig(AppConfig): + default_auto_field = 'django.db.models.BigAutoField' + name = 'brand' diff --git a/brand/migrations/0001_initial.py b/brand/migrations/0001_initial.py new file mode 100644 index 00000000..0ac08cb0 --- /dev/null +++ b/brand/migrations/0001_initial.py @@ -0,0 +1,24 @@ +# Generated by Django 4.0.6 on 2022-07-31 17:24 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ] + + operations = [ + migrations.CreateModel( + name='Brand', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('title', models.CharField(max_length=32)), + ('description', models.TextField()), + ('established_at', models.DateTimeField()), + ('city', models.CharField(max_length=128)), + ], + ), + ] diff --git a/brand/migrations/0002_alter_brand_established_at_alter_brand_title.py b/brand/migrations/0002_alter_brand_established_at_alter_brand_title.py new file mode 100644 index 00000000..d92cc0b8 --- /dev/null +++ b/brand/migrations/0002_alter_brand_established_at_alter_brand_title.py @@ -0,0 +1,23 @@ +# Generated by Django 4.0.6 on 2022-07-31 19:37 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('brand', '0001_initial'), + ] + + operations = [ + migrations.AlterField( + model_name='brand', + name='established_at', + field=models.DateTimeField(auto_now=True), + ), + migrations.AlterField( + model_name='brand', + name='title', + field=models.CharField(max_length=32, unique=True), + ), + ] diff --git a/brand/migrations/__init__.py b/brand/migrations/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/brand/models.py b/brand/models.py new file mode 100644 index 00000000..8a08a5f0 --- /dev/null +++ b/brand/models.py @@ -0,0 +1,10 @@ +from django.db import models + +# Create your models here. + +class Brand(models.Model): + + title = models.CharField(max_length=32, unique=True) + description = models.TextField() + established_at = models.DateTimeField(auto_now=True) + city = models.CharField(max_length=128) \ No newline at end of file diff --git a/brand/serializers.py b/brand/serializers.py new file mode 100644 index 00000000..fa8a6706 --- /dev/null +++ b/brand/serializers.py @@ -0,0 +1,8 @@ +from rest_framework import serializers +from .models import Brand + +class BrandSerilizer(serializers.ModelSerializer): + + class Meta: + model = Brand + fields = '__all__' \ No newline at end of file diff --git a/brand/tests.py b/brand/tests.py new file mode 100644 index 00000000..7ce503c2 --- /dev/null +++ b/brand/tests.py @@ -0,0 +1,3 @@ +from django.test import TestCase + +# Create your tests here. diff --git a/brand/urls.py b/brand/urls.py new file mode 100644 index 00000000..dd10a473 --- /dev/null +++ b/brand/urls.py @@ -0,0 +1,11 @@ +from django.urls import path +from . import views + +app_name = "brand" + +urlpatterns = [ + path("add/", views.add_brand, name="add_brand"), + path("all/", views.get_brands, name="all_brands"), + path("update/", views.update_brand, name="update_brand"), + path("delete/", views.delete_brand, name="delete_brand"), +] \ No newline at end of file diff --git a/brand/views.py b/brand/views.py new file mode 100644 index 00000000..2aa7204b --- /dev/null +++ b/brand/views.py @@ -0,0 +1,65 @@ +# from django.shortcuts import render + +from rest_framework.decorators import api_view +from rest_framework.request import Request +from rest_framework.response import Response +from rest_framework import status +from brand.models import Brand +from .serializers import BrandSerilizer +# Create your views here. + + +@api_view(['POST']) +def add_brand(request: Request) -> Response: + + brand = BrandSerilizer(data=request.data) + + if brand.is_valid(): + brand.save() + return Response({"msg" : "added succefully!"}) + return Response({"msg": brand.errors}) + +@api_view(['GET']) +def get_brands(request: Request) -> Response: + + if "max" and "min" in request.query_params: + + maximumm = int(request.query_params.get("max")) + minmumm = int(request.query_params.get("min")) + + brands = Brand.objects.all()[minmumm:maximumm] + + elif "search" in request.query_params: + print("went") + brand_title = request.query_params.get("search") + brands = Brand.objects.filter(title=brand_title) + + else: + + brands = Brand.objects.order_by('-id').all() + + data = BrandSerilizer(brands, many=True).data + + return Response(data, status=status.HTTP_200_OK) + + +@api_view(["PUT"]) +def update_brand(request: Request, brand_id) -> Response: + + brand = Brand.objects.get(id=brand_id) + + data = BrandSerilizer(instance=brand, data=request.data,partial=True) + + if data.is_valid(): + data.save() + return Response({"msg": "updated succefully"}, status=status.HTTP_201_CREATED) + + +@api_view(["DELETE"]) +def delete_brand(request: Request, brand_id) -> Response: + + brand = Brand.objects.get(id=brand_id) + + brand.delete() + + return Response({"msg":"brand deleted succefully"}) \ No newline at end of file diff --git a/db.sqlite3 b/db.sqlite3 new file mode 100644 index 00000000..41157abf Binary files /dev/null and b/db.sqlite3 differ diff --git a/eCommerce/__init__.py b/eCommerce/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/eCommerce/asgi.py b/eCommerce/asgi.py new file mode 100644 index 00000000..534f83bb --- /dev/null +++ b/eCommerce/asgi.py @@ -0,0 +1,16 @@ +""" +ASGI config for eCommerce project. + +It exposes the ASGI callable as a module-level variable named ``application``. + +For more information on this file, see +https://docs.djangoproject.com/en/4.0/howto/deployment/asgi/ +""" + +import os + +from django.core.asgi import get_asgi_application + +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'eCommerce.settings') + +application = get_asgi_application() diff --git a/eCommerce/settings.py b/eCommerce/settings.py new file mode 100644 index 00000000..6a93bc03 --- /dev/null +++ b/eCommerce/settings.py @@ -0,0 +1,126 @@ +""" +Django settings for eCommerce project. + +Generated by 'django-admin startproject' using Django 4.0.6. + +For more information on this file, see +https://docs.djangoproject.com/en/4.0/topics/settings/ + +For the full list of settings and their values, see +https://docs.djangoproject.com/en/4.0/ref/settings/ +""" + +from pathlib import Path + +# Build paths inside the project like this: BASE_DIR / 'subdir'. +BASE_DIR = Path(__file__).resolve().parent.parent + + +# Quick-start development settings - unsuitable for production +# See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ + +# SECURITY WARNING: keep the secret key used in production secret! +SECRET_KEY = 'django-insecure-9xm!m&_m!=ud35%l#xaqjpc6yt9pmo+yj#7z@pxu2$91c4#dtz' + +# SECURITY WARNING: don't run with debug turned on in production! +DEBUG = True + +ALLOWED_HOSTS = [] + + +# Application definition + +INSTALLED_APPS = [ + 'django.contrib.admin', + 'django.contrib.auth', + 'django.contrib.contenttypes', + 'django.contrib.sessions', + 'django.contrib.messages', + 'django.contrib.staticfiles', + 'rest_framework', + 'product', + 'brand', +] + +MIDDLEWARE = [ + 'django.middleware.security.SecurityMiddleware', + 'django.contrib.sessions.middleware.SessionMiddleware', + 'django.middleware.common.CommonMiddleware', + 'django.middleware.csrf.CsrfViewMiddleware', + 'django.contrib.auth.middleware.AuthenticationMiddleware', + 'django.contrib.messages.middleware.MessageMiddleware', + 'django.middleware.clickjacking.XFrameOptionsMiddleware', +] + +ROOT_URLCONF = 'eCommerce.urls' + +TEMPLATES = [ + { + 'BACKEND': 'django.template.backends.django.DjangoTemplates', + 'DIRS': [], + 'APP_DIRS': True, + 'OPTIONS': { + 'context_processors': [ + 'django.template.context_processors.debug', + 'django.template.context_processors.request', + 'django.contrib.auth.context_processors.auth', + 'django.contrib.messages.context_processors.messages', + ], + }, + }, +] + +WSGI_APPLICATION = 'eCommerce.wsgi.application' + + +# Database +# https://docs.djangoproject.com/en/4.0/ref/settings/#databases + +DATABASES = { + 'default': { + 'ENGINE': 'django.db.backends.sqlite3', + 'NAME': BASE_DIR / 'db.sqlite3', + } +} + + +# Password validation +# https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators + +AUTH_PASSWORD_VALIDATORS = [ + { + 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', + }, + { + 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', + }, + { + 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', + }, + { + 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', + }, +] + + +# Internationalization +# https://docs.djangoproject.com/en/4.0/topics/i18n/ + +LANGUAGE_CODE = 'en-us' + +TIME_ZONE = 'UTC' + +USE_I18N = True + +USE_TZ = True + + +# Static files (CSS, JavaScript, Images) +# https://docs.djangoproject.com/en/4.0/howto/static-files/ + +STATIC_URL = 'static/' + +# Default primary key field type +# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field + +DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' diff --git a/eCommerce/urls.py b/eCommerce/urls.py new file mode 100644 index 00000000..73a3c39a --- /dev/null +++ b/eCommerce/urls.py @@ -0,0 +1,23 @@ +"""eCommerce URL Configuration + +The `urlpatterns` list routes URLs to views. For more information please see: + https://docs.djangoproject.com/en/4.0/topics/http/urls/ +Examples: +Function views + 1. Add an import: from my_app import views + 2. Add a URL to urlpatterns: path('', views.home, name='home') +Class-based views + 1. Add an import: from other_app.views import Home + 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') +Including another URLconf + 1. Import the include() function: from django.urls import include, path + 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) +""" +from django.contrib import admin +from django.urls import path, include + +urlpatterns = [ + path('admin/', admin.site.urls), + path('brands/', include("brand.urls")), + path('products/', include("product.urls")), +] diff --git a/eCommerce/wsgi.py b/eCommerce/wsgi.py new file mode 100644 index 00000000..18d60638 --- /dev/null +++ b/eCommerce/wsgi.py @@ -0,0 +1,16 @@ +""" +WSGI config for eCommerce project. + +It exposes the WSGI callable as a module-level variable named ``application``. + +For more information on this file, see +https://docs.djangoproject.com/en/4.0/howto/deployment/wsgi/ +""" + +import os + +from django.core.wsgi import get_wsgi_application + +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'eCommerce.settings') + +application = get_wsgi_application() diff --git a/manage.py b/manage.py new file mode 100755 index 00000000..aa3d79c9 --- /dev/null +++ b/manage.py @@ -0,0 +1,22 @@ +#!/usr/bin/env python +"""Django's command-line utility for administrative tasks.""" +import os +import sys + + +def main(): + """Run administrative tasks.""" + os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'eCommerce.settings') + try: + from django.core.management import execute_from_command_line + except ImportError as exc: + raise ImportError( + "Couldn't import Django. Are you sure it's installed and " + "available on your PYTHONPATH environment variable? Did you " + "forget to activate a virtual environment?" + ) from exc + execute_from_command_line(sys.argv) + + +if __name__ == '__main__': + main() diff --git a/product/__init__.py b/product/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/product/admin.py b/product/admin.py new file mode 100644 index 00000000..8c38f3f3 --- /dev/null +++ b/product/admin.py @@ -0,0 +1,3 @@ +from django.contrib import admin + +# Register your models here. diff --git a/product/apps.py b/product/apps.py new file mode 100644 index 00000000..235a3339 --- /dev/null +++ b/product/apps.py @@ -0,0 +1,6 @@ +from django.apps import AppConfig + + +class ProductConfig(AppConfig): + default_auto_field = 'django.db.models.BigAutoField' + name = 'product' diff --git a/product/migrations/0001_initial.py b/product/migrations/0001_initial.py new file mode 100644 index 00000000..f72afd42 --- /dev/null +++ b/product/migrations/0001_initial.py @@ -0,0 +1,29 @@ +# Generated by Django 4.0.6 on 2022-07-31 17:24 + +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ('brand', '0001_initial'), + ] + + operations = [ + migrations.CreateModel( + name='Product', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('name', models.CharField(max_length=128)), + ('description', models.TextField()), + ('image_url', models.URLField()), + ('price', models.DecimalField(decimal_places=2, max_digits=5)), + ('quantity', models.IntegerField()), + ('is_active', models.BooleanField()), + ('brand', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='brand.brand')), + ], + ), + ] diff --git a/product/migrations/0002_alter_product_is_active.py b/product/migrations/0002_alter_product_is_active.py new file mode 100644 index 00000000..f03a337f --- /dev/null +++ b/product/migrations/0002_alter_product_is_active.py @@ -0,0 +1,18 @@ +# Generated by Django 4.0.6 on 2022-07-31 19:37 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('product', '0001_initial'), + ] + + operations = [ + migrations.AlterField( + model_name='product', + name='is_active', + field=models.BooleanField(default=True), + ), + ] diff --git a/product/migrations/__init__.py b/product/migrations/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/product/models.py b/product/models.py new file mode 100644 index 00000000..2d26957a --- /dev/null +++ b/product/models.py @@ -0,0 +1,14 @@ +from ast import mod +from django.db import models +from brand.models import Brand +# Create your models here. + +class Product(models.Model): + + brand = models.ForeignKey(Brand, on_delete=models.CASCADE) + name = models.CharField(max_length=128) + description = models.TextField() + image_url = models.URLField() + price = models.DecimalField(max_digits=5,decimal_places=2) + quantity = models.IntegerField() + is_active = models.BooleanField(default=True) \ No newline at end of file diff --git a/product/serializers.py b/product/serializers.py new file mode 100644 index 00000000..f438aaaa --- /dev/null +++ b/product/serializers.py @@ -0,0 +1,9 @@ +from rest_framework import serializers +from .models import Product + + +class ProductSerilizer(serializers.ModelSerializer): + + class Meta: + model = Product + fields = '__all__' \ No newline at end of file diff --git a/product/tests.py b/product/tests.py new file mode 100644 index 00000000..7ce503c2 --- /dev/null +++ b/product/tests.py @@ -0,0 +1,3 @@ +from django.test import TestCase + +# Create your tests here. diff --git a/product/urls.py b/product/urls.py new file mode 100644 index 00000000..2bac5df0 --- /dev/null +++ b/product/urls.py @@ -0,0 +1,11 @@ +from django.urls import path +from . import views + +app_name = "product" + +urlpatterns = [ + path("add/", views.add_product, name="add_product"), + path("all/", views.get_products, name="all_products"), + path("update/", views.update_product, name="update_product"), + path("delete/", views.delete_product, name="delete_product"), +] \ No newline at end of file diff --git a/product/views.py b/product/views.py new file mode 100644 index 00000000..b2fca006 --- /dev/null +++ b/product/views.py @@ -0,0 +1,58 @@ +# from django.shortcuts import render +from rest_framework.decorators import api_view +from rest_framework.request import Request +from rest_framework.response import Response +from .serializers import ProductSerilizer +from rest_framework import status +from .models import Product +# Create your views here. + + +@api_view(["POST"]) +def add_product(request: Request) -> Response: + + product = ProductSerilizer(data=request.data) + + if product.is_valid(): + product.save() + return Response({"msg" : "added succefully!"}) + return Response({"msg": product.errors}) + + +@api_view(['GET']) +def get_products(request: Request) -> Response: + + + + if "brand" in request.query_params : + + brand_id = int(request.query_params.get("brand")) + products = Product.objects.filter(brand=brand_id) + data = ProductSerilizer(products, many=True).data + + else: + products = Product.objects.order_by('-id').all() + data = ProductSerilizer(products, many=True).data + + return Response(data, status=status.HTTP_200_OK) + + +@api_view(["PUT"]) +def update_product(request: Request, product_id) -> Response: + + product = Product.objects.get(id=product_id) + + data = ProductSerilizer(instance=product, data=request.data,partial=True) + + if data.is_valid(): + data.save() + return Response({"msg": "updated succefully"}, status=status.HTTP_201_CREATED) + +@api_view(["DELETE"]) +def delete_product(request: Request, product_id) -> Response: + + product = Product.objects.get(id=product_id) + + product.delete() + + return Response({"msg":"product deleted succefully"}) \ No newline at end of file diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 00000000..ff453381 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,5 @@ +asgiref==3.5.2 +Django==4.0.6 +djangorestframework==3.13.1 +pytz==2022.1 +sqlparse==0.4.2