initial app django with users products and shopping_car

This commit is contained in:
programador 2025-03-25 13:19:47 -05:00
parent 9fd5fb24fe
commit 75b7a75993
20 changed files with 401 additions and 0 deletions

0
apps/orders/__init__.py Normal file
View File

3
apps/orders/admin.py Normal file
View File

@ -0,0 +1,3 @@
from django.contrib import admin
# Register your models here.

6
apps/orders/apps.py Normal file
View File

@ -0,0 +1,6 @@
from django.apps import AppConfig
class OrdersConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'apps.orders'

View File

View File

@ -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']

View File

@ -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']

3
apps/orders/tests.py Normal file
View File

@ -0,0 +1,3 @@
from django.test import TestCase
# Create your tests here.

3
apps/orders/views.py Normal file
View File

@ -0,0 +1,3 @@
from django.shortcuts import render
# Create your views here.

0
apps/users/__init__.py Normal file
View File

3
apps/users/admin.py Normal file
View File

@ -0,0 +1,3 @@
from django.contrib import admin
# Register your models here.

6
apps/users/apps.py Normal file
View File

@ -0,0 +1,6 @@
from django.apps import AppConfig
class UsersConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'apps.users'

41
apps/users/models.py Normal file
View File

@ -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

3
apps/users/tests.py Normal file
View File

@ -0,0 +1,3 @@
from django.test import TestCase
# Create your tests here.

3
apps/users/views.py Normal file
View File

@ -0,0 +1,3 @@
from django.shortcuts import render
# Create your views here.

0
core/__init__.py Normal file
View File

16
core/asgi.py Normal file
View File

@ -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()

201
core/settings.py Normal file
View File

@ -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)),
}

22
core/urls.py Normal file
View File

@ -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),
]

16
core/wsgi.py Normal file
View File

@ -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()

22
manage.py Normal file
View File

@ -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()