Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
89 changes: 65 additions & 24 deletions app/app/settings.py
Original file line number Diff line number Diff line change
@@ -1,32 +1,19 @@
"""
Django settings for app project.

Generated by 'django-admin startproject' using Django 4.0.1.

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
from decouple import config, Csv

# 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-h-h69cr05lmc*w4vtkf+5qltg8#&#xf8fe(v9j9oxs-*-^#vjd'
SECRET_KEY = config('SECRET_KEY')

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []
DEBUG = config('DEBUG', default=False, cast=bool)

ALLOWED_HOSTS = config('ALLOWED_HOSTS', default='localhost,127.0.0.1', cast=Csv())

# Application definition

Expand All @@ -37,6 +24,7 @@
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'core'
]

Expand Down Expand Up @@ -70,18 +58,25 @@

WSGI_APPLICATION = 'app.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',
'ENGINE': 'django.db.backends.postgresql',
'NAME': config('POSTGRES_DATABASE'),
'USER': config('POSTGRES_USER'),
'PASSWORD': config('POSTGRES_PASSWORD'),
'HOST': config('POSTGRES_HOST', default='localhost'),
'PORT': config('POSTGRES_PORT', default='5432'),
}
}


# 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

Expand All @@ -100,6 +95,13 @@
},
]

# PASSWORD_HASHERS = [
# "django.contrib.auth.hashers.PBKDF2PasswordHasher",
# "django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher",
# "django.contrib.auth.hashers.Argon2PasswordHasher",
# "django.contrib.auth.hashers.BCryptSHA256PasswordHasher",
# "django.contrib.auth.hashers.ScryptPasswordHasher",
# ]

# Internationalization
# https://docs.djangoproject.com/en/4.0/topics/i18n/
Expand All @@ -112,7 +114,6 @@

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.0/howto/static-files/

Expand All @@ -123,4 +124,44 @@

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

AUTH_USER_MODEL = 'core.User'
AUTH_USER_MODEL = 'core.User'

# Django Rest Framework settings
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_simplejwt.authentication.JWTAuthentication',
),
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
),
}


# Email settings
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = config('EMAIL_HOST')
EMAIL_PORT = config('EMAIL_PORT', cast=int)
EMAIL_USE_TLS = config('EMAIL_USE_TLS', cast=bool)
EMAIL_HOST_USER = config('EMAIL_HOST_USER')
EMAIL_HOST_PASSWORD = config('EMAIL_HOST_PASSWORD')


from datetime import timedelta

SIMPLE_JWT = {
'ACCESS_TOKEN_LIFETIME': timedelta(hours=2),
'REFRESH_TOKEN_LIFETIME': timedelta(days=1),
'ROTATE_REFRESH_TOKENS': False,
'BLACKLIST_AFTER_ROTATION': True,
'ALGORITHM': 'HS256',
'SIGNING_KEY': SECRET_KEY,
'VERIFYING_KEY': None,
'AUDIENCE': None,
'ISSUER': None,
'AUTH_HEADER_TYPES': ('Bearer',),
'USER_ID_FIELD': 'id',
'USER_ID_CLAIM': 'user_id',
'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',),
'TOKEN_TYPE_CLAIM': 'token_type',
'JTI_CLAIM': 'jti',
}
3 changes: 2 additions & 1 deletion app/app/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,9 @@
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from django.urls import path, include

urlpatterns = [
path('admin/', admin.site.urls),
path('api/', include('core.urls'))
]
10 changes: 8 additions & 2 deletions app/core/admin.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
"""Manage admin page for main app."""

# from django.contrib import admin

from django.contrib import admin
from .models import User, Product, Category, Order, OrderItem
# Register your models here.

admin.site.register(User)
admin.site.register(Category)
admin.site.register(Product)
admin.site.register(Order)
admin.site.register(OrderItem)
31 changes: 31 additions & 0 deletions app/core/migrations/0002_category_product.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
# Generated by Django 5.0.7 on 2024-07-18 23:36

import django.db.models.deletion
from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('core', '0001_initial'),
]

operations = [
migrations.CreateModel(
name='Category',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=255)),
('cover', models.URLField(null=True)),
],
),
migrations.CreateModel(
name='Product',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=255)),
('price', models.FloatField()),
('category', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='core.category')),
],
),
]
40 changes: 40 additions & 0 deletions app/core/migrations/0003_alter_category_name_order_orderitem.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
# Generated by Django 5.0.7 on 2024-07-19 11:04

import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('core', '0002_category_product'),
]

operations = [
migrations.AlterField(
model_name='category',
name='name',
field=models.CharField(max_length=255, unique=True),
),
migrations.CreateModel(
name='Order',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
('status', models.CharField(choices=[('pending', 'Pending'), ('completed', 'Completed'), ('cancelled', 'Cancelled')], max_length=20)),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
migrations.CreateModel(
name='OrderItem',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('quantity', models.PositiveIntegerField()),
('price', models.DecimalField(decimal_places=2, max_digits=10)),
('order', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='items', to='core.order')),
('product', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='core.product')),
],
),
]
44 changes: 41 additions & 3 deletions app/core/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, \
PermissionsMixin
from datetime import datetime
# Create your models here.


Expand All @@ -13,7 +14,6 @@ def create_user(self, email, password=None, **extra_fields):
"""Create_user method creates and saves new user objects."""
if not email:
raise ValueError('User must have valid email address')

user = self.model(email=self.normalize_email(email), **extra_fields)
user.set_password(password)
user.save(using=self._db)
Expand All @@ -36,7 +36,45 @@ class User(AbstractBaseUser, PermissionsMixin):
name = models.CharField(max_length=255)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)

objects = UserManager()

USERNAME_FIELD = 'email'

class Category(models.Model):

name = models.CharField(max_length=255, null=False, unique=True)
cover = models.URLField(null=True)
def __str__(self)->str:
return f"{self.name}"

class Product(models.Model):

name = models.CharField(max_length=255, null=False)
price = models.FloatField(null=False)
category = models.ForeignKey(Category, on_delete=models.CASCADE)
def __str__(self)->str:
return f"{self.name}"

class Order(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
status = models.CharField(max_length=20, choices=[
('pending', 'Pending'),
('completed', 'Completed'),
('cancelled', 'Cancelled')
], default="Pending")

def __str__(self):
return f"Order {self.id} by {self.user.email}"


class OrderItem(models.Model):
order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name='items')
product = models.ForeignKey(Product, on_delete=models.CASCADE)
quantity = models.PositiveIntegerField()
price = models.DecimalField(max_digits=10, decimal_places=2)

def __str__(self):
return f"{self.quantity} of {self.product.name} in order {self.order.id}"


5 changes: 5 additions & 0 deletions app/core/permissions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
from rest_framework.permissions import BasePermission

class IsStaff(BasePermission):
def has_permission(self, request, view):
return request.user and request.user.is_staff
Loading