diff --git a/apps/orders/__init__.py b/apps/orders/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/apps/orders/admin.py b/apps/orders/admin.py new file mode 100644 index 0000000..8c38f3f --- /dev/null +++ b/apps/orders/admin.py @@ -0,0 +1,3 @@ +from django.contrib import admin + +# Register your models here. diff --git a/apps/orders/apps.py b/apps/orders/apps.py new file mode 100644 index 0000000..4f436a5 --- /dev/null +++ b/apps/orders/apps.py @@ -0,0 +1,6 @@ +from django.apps import AppConfig + + +class OrdersConfig(AppConfig): + default_auto_field = 'django.db.models.BigAutoField' + name = 'apps.orders' diff --git a/apps/orders/models/__init__.py b/apps/orders/models/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/apps/orders/models/product.py b/apps/orders/models/product.py new file mode 100644 index 0000000..e77ac57 --- /dev/null +++ b/apps/orders/models/product.py @@ -0,0 +1,27 @@ +from django.db import models + +class Product(models.Model): + name = models.CharField(max_length=255) + description = models.TextField() + price = models.DecimalField(max_digits=10, decimal_places=2) + imagen = models.ImageField( + upload_to='product', + verbose_name='imagen', + max_length=355, + blank=True, + null=True + ) + created_at = models.DateTimeField('created at', auto_now_add=True, + help_text='Date time on which the object was created.') + modified_at = models.DateTimeField('modified at', auto_now=True, + help_text='Date time on which the object was last modified.') + + is_active = models.BooleanField(default=True) + + def __str__(self): + return self.name + + class Meta: + verbose_name = 'Producto' + verbose_name_plural = 'Productos' + ordering = ['name'] diff --git a/apps/orders/models/shoping_car.py b/apps/orders/models/shoping_car.py new file mode 100644 index 0000000..b419181 --- /dev/null +++ b/apps/orders/models/shoping_car.py @@ -0,0 +1,26 @@ +from django.db import models +from apps.users.models import CustomUser + +class ShoppingCar(models.Model): + user = models.ForeignKey( + CustomUser, + on_delete = models.CASCADE, + blank=True, null=True + ) + name = models.ForeignKey( + CustomUser, + on_delete = models.CASCADE, + blank=True, null=True + ) + quantity = models.FloatField(default=1) + price = models.DecimalField(max_digits=10, decimal_places=2) + created_at = models.DateTimeField('created at', auto_now_add=True) + modified_at = models.DateTimeField('modified at', auto_now=True) + + def __str__(self): + return self.name + + class Meta: + verbose_name = 'Producto' + verbose_name_plural = 'Productos' + ordering = ['name'] diff --git a/apps/orders/tests.py b/apps/orders/tests.py new file mode 100644 index 0000000..7ce503c --- /dev/null +++ b/apps/orders/tests.py @@ -0,0 +1,3 @@ +from django.test import TestCase + +# Create your tests here. diff --git a/apps/orders/views.py b/apps/orders/views.py new file mode 100644 index 0000000..91ea44a --- /dev/null +++ b/apps/orders/views.py @@ -0,0 +1,3 @@ +from django.shortcuts import render + +# Create your views here. diff --git a/apps/users/__init__.py b/apps/users/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/apps/users/admin.py b/apps/users/admin.py new file mode 100644 index 0000000..8c38f3f --- /dev/null +++ b/apps/users/admin.py @@ -0,0 +1,3 @@ +from django.contrib import admin + +# Register your models here. diff --git a/apps/users/apps.py b/apps/users/apps.py new file mode 100644 index 0000000..2bb189c --- /dev/null +++ b/apps/users/apps.py @@ -0,0 +1,6 @@ +from django.apps import AppConfig + + +class UsersConfig(AppConfig): + default_auto_field = 'django.db.models.BigAutoField' + name = 'apps.users' diff --git a/apps/users/models.py b/apps/users/models.py new file mode 100644 index 0000000..1b9b29d --- /dev/null +++ b/apps/users/models.py @@ -0,0 +1,41 @@ +from django.contrib.auth.models import Group, AbstractUser, BaseUserManager +from django.db import models +from django.core.validators import MaxValueValidator + +class CustomUserManager(BaseUserManager): + def create_user(self, email, password=None, **extra_fields): + if not email: + raise ValueError('El email es obligatorio') + email = self.normalize_email(email) + user = self.model(email=email, **extra_fields) + user.set_password(password) + user.save(using=self._db) + return user + + def create_superuser(self, email, password=None, **extra_fields): + extra_fields.setdefault('is_staff', True) + extra_fields.setdefault('is_superuser', True) + #extra_fields.setdefault('groups', Group.objects.get(name='Super Administrador')) + return self.create_user(email, password, **extra_fields) + +class CustomUser(AbstractUser): + email = models.EmailField(unique=True) + first_name = models.CharField(max_length=30, blank=True) + last_name = models.CharField(max_length=30, blank=True) + is_active = models.BooleanField(default=True) + is_staff = models.BooleanField(default=False) + groups = models.ForeignKey(Group, on_delete=models.CASCADE, + null=True, blank=True, verbose_name='rol') + USERNAME_FIELD = 'email' + REQUIRED_FIELDS = [] + + objects = CustomUserManager() + + def __str__(self): + if self.last_name and self.first_name: + return f'{self.first_name} {self.last_name}' + elif self.first_name: + return self.first_name + elif self.last_name: + return self.last_name + return self.email diff --git a/apps/users/tests.py b/apps/users/tests.py new file mode 100644 index 0000000..7ce503c --- /dev/null +++ b/apps/users/tests.py @@ -0,0 +1,3 @@ +from django.test import TestCase + +# Create your tests here. diff --git a/apps/users/views.py b/apps/users/views.py new file mode 100644 index 0000000..91ea44a --- /dev/null +++ b/apps/users/views.py @@ -0,0 +1,3 @@ +from django.shortcuts import render + +# Create your views here. diff --git a/core/__init__.py b/core/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/core/asgi.py b/core/asgi.py new file mode 100644 index 0000000..3b35c6b --- /dev/null +++ b/core/asgi.py @@ -0,0 +1,16 @@ +""" +ASGI config for core 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.2/howto/deployment/asgi/ +""" + +import os + +from django.core.asgi import get_asgi_application + +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'core.settings') + +application = get_asgi_application() diff --git a/core/settings.py b/core/settings.py new file mode 100644 index 0000000..88cd6d2 --- /dev/null +++ b/core/settings.py @@ -0,0 +1,201 @@ +""" +Django settings for core project. + +Generated by 'django-admin startproject' using Django 4.2.7. + +For more information on this file, see +https://docs.djangoproject.com/en/4.2/topics/settings/ + +For the full list of settings and their values, see +https://docs.djangoproject.com/en/4.2/ref/settings/ +""" +import environ +import os +import datetime as dt +from pathlib import Path + +from common.const_and_variables import BOOLEAN_VALIDS + + +# Build paths inside the project like this: BASE_DIR / 'subdir'. +BASE_DIR = Path(__file__).resolve().parent.parent +env = environ.Env( + DEBUG=(bool, False) +) + +# Leer el archivo .env +environ.Env.read_env(os.path.join(BASE_DIR, '.env')) + +API_BASE_URL = env('API_BASE_URL') + +# Quick-start development settings - unsuitable for production +# See https://docs.djangoproject.com/en/4.2/howto/deployment/checklist/ + +# SECURITY WARNING: keep the secret key used in production secret! +SECRET_KEY = env('SECRET_KEY') + +# SECURITY WARNING: don't run with debug turned on in production! +DEBUG = env('DEBUG', False) in BOOLEAN_VALIDS + +ALLOWED_HOSTS = env.list('ALLOWED_HOSTS', default=[]) +CSRF_TRUSTED_ORIGINS = env.list('CSRF_TRUSTED_ORIGINS', default=[]) + + +CORS_ALLOW_ALL_ORIGINS = True if DEBUG else () + + +# Application definition + +DJANGO_APPS = [ + 'django.contrib.admin', + 'django.contrib.auth', + 'django.contrib.contenttypes', + 'django.contrib.sessions', + 'django.contrib.messages', + 'django.contrib.staticfiles', +] + +EXTERNAL_APPS = [ + 'rest_framework', + 'rest_framework_simplejwt', + 'rest_framework_simplejwt.token_blacklist', + 'corsheaders', + 'drf_yasg', + 'django_filters', +] + +PROJECT_APPS = [ + 'apps.users', + 'apps.orders' +] + +INSTALLED_APPS = EXTERNAL_APPS + DJANGO_APPS + PROJECT_APPS + +AUTH_USER_MODEL = 'users.CustomUser' + + +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 = 'core.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 = 'core.wsgi.application' + + +# Database +# https://docs.djangoproject.com/en/4.2/ref/settings/#databases + +DATABASES = { + 'default': { + 'ENGINE': env('DATABASE_ENGINE'), + 'PASSWORD': env('DATABASE_PASSWORD'), + 'NAME': env('DATABASE_NAME'), + 'USER': env('DATABASE_USER'), + 'HOST': env('DATABASE_HOST'), + 'PORT': env('DATABASE_PORT'), + 'OPTIONS': { + 'client_encoding': 'UTF-8' + }, + }, +} + + +# Password validation +# https://docs.djangoproject.com/en/4.2/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.2/topics/i18n/ + +LANGUAGE_CODE = 'es-CO' + +LANGUAGES = ( + ('es', 'Spanish'), + ('en', 'English'), +) + +DATE_FORMAT = 'd-m-Y' # Formato de fecha: día-mes-año +DATETIME_FORMAT = 'd-m-Y H:i' # Formato de fecha y hora +USE_L10N = False + +TIME_ZONE = 'America/Bogota' +USE_I18N = True +USE_L10N = True +USE_TZ = True + + +# Static files (CSS, JavaScript, Images) +# https://docs.djangoproject.com/en/4.2/howto/static-files/ + +STATIC_URL = '/static/' +STATIC_ROOT = os.path.join(BASE_DIR, 'static/') + +MEDIA_URL = '/media/' +MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') + +X_FRAME_OPTIONS = "SAMEORIGIN" +SILENCED_SYSTEM_CHECKS = ["security.W019"] + +# Default primary key field type +# https://docs.djangoproject.com/en/4.2/ref/settings/#default-auto-field + +DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' + + +REST_FRAMEWORK = { + 'DEFAULT_AUTHENTICATION_CLASSES': ( + 'rest_framework_simplejwt.authentication.JWTAuthentication', + ), + 'EXCEPTION_HANDLER': 'common.exceptions.custom_validation_error', + 'DATETIME_FORMAT': "%d-%m-%Y %H:%M:%S", + "DATE_FORMAT": "%d-%m-%Y" +} + +SIMPLE_JWT = { + "ACCESS_TOKEN_LIFETIME": dt.timedelta( + days=env.int('ACCESS_TOKEN_LIFETIME_DAYS', default=0), + hours=env.int('ACCESS_TOKEN_LIFETIME_HOURS', default=0), + minutes=env.int('ACCESS_TOKEN_LIFETIME_MINUTES', default=10)), + "REFRESH_TOKEN_LIFETIME": dt.timedelta( + days=env.int('REFRESH_TOKEN_LIFETIME_DAYS', default=0), + hours=env.int('REFRESH_TOKEN_LIFETIME_HOURS', default=0), + minutes=env.int('REFRESH_TOKEN_LIFETIME_MINUTES', default=30)), +} \ No newline at end of file diff --git a/core/urls.py b/core/urls.py new file mode 100644 index 0000000..3b2f61e --- /dev/null +++ b/core/urls.py @@ -0,0 +1,22 @@ +""" +URL configuration for core project. + +The `urlpatterns` list routes URLs to views. For more information please see: + https://docs.djangoproject.com/en/4.2/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 + +urlpatterns = [ + path('admin/', admin.site.urls), +] diff --git a/core/wsgi.py b/core/wsgi.py new file mode 100644 index 0000000..f44964d --- /dev/null +++ b/core/wsgi.py @@ -0,0 +1,16 @@ +""" +WSGI config for core 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.2/howto/deployment/wsgi/ +""" + +import os + +from django.core.wsgi import get_wsgi_application + +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'core.settings') + +application = get_wsgi_application() diff --git a/manage.py b/manage.py new file mode 100644 index 0000000..f2a662c --- /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', 'core.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()