Compare commits
10 commits
25cc8f959d
...
54e0c2b793
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
54e0c2b793 | ||
|
|
2e43109553 | ||
|
|
551ae8691b | ||
|
|
7d2454c3be | ||
|
|
51dff4ce8f | ||
|
|
ae040b2d29 | ||
|
|
b964aef464 | ||
|
|
04ce180ac1 | ||
|
|
3ac14fc64f | ||
|
|
97d7cb359a |
20 changed files with 460 additions and 1 deletions
24
.gitignore
vendored
Executable file
24
.gitignore
vendored
Executable file
|
|
@ -0,0 +1,24 @@
|
|||
# Ignore virtual environment
|
||||
venv/
|
||||
|
||||
# Ignore Django migrations
|
||||
**/migrations/
|
||||
|
||||
# Ignore media files
|
||||
**/media/
|
||||
media/
|
||||
|
||||
# Ignore pycache
|
||||
**/__pycache__/
|
||||
__pycache__/
|
||||
|
||||
# Ignore static files
|
||||
**/static/
|
||||
static/
|
||||
|
||||
# Ignore staticfiles directory
|
||||
**/staticfiles/
|
||||
staticfiles/
|
||||
|
||||
# Ignore logs
|
||||
*.log
|
||||
0
LICENSE
Normal file → Executable file
0
LICENSE
Normal file → Executable file
2
README.md
Normal file → Executable file
2
README.md
Normal file → Executable file
|
|
@ -1,2 +1,2 @@
|
|||
# simple-plant-archive-django
|
||||
Django-based app for building a customer-oriented product catalog with archiving features.
|
||||
Django-based rest api for building a customer-oriented product catalog with archiving features.
|
||||
|
|
|
|||
0
plant_catalog/catalog/__init__.py
Executable file
0
plant_catalog/catalog/__init__.py
Executable file
7
plant_catalog/catalog/admin.py
Executable file
7
plant_catalog/catalog/admin.py
Executable file
|
|
@ -0,0 +1,7 @@
|
|||
from django.contrib import admin
|
||||
from .models import Plant
|
||||
|
||||
@admin.register(Plant)
|
||||
class PlantAdmin(admin.ModelAdmin):
|
||||
list_display = ('name', 'image')
|
||||
search_fields = ('name',)
|
||||
25
plant_catalog/catalog/api_views.py
Executable file
25
plant_catalog/catalog/api_views.py
Executable file
|
|
@ -0,0 +1,25 @@
|
|||
# catalog/api_views.py
|
||||
|
||||
from rest_framework import generics
|
||||
from rest_framework.parsers import MultiPartParser, FormParser, JSONParser
|
||||
from rest_framework.filters import SearchFilter
|
||||
|
||||
from .permissions import IsAuthenticatedOrReadOnly
|
||||
from .models import Plant
|
||||
from .serializers import PlantSerializer
|
||||
|
||||
# List and Create Plants
|
||||
class PlantListCreateAPIView(generics.ListCreateAPIView):
|
||||
queryset = Plant.objects.all()
|
||||
serializer_class = PlantSerializer
|
||||
parser_classes = [JSONParser, MultiPartParser, FormParser] # Allow file uploads
|
||||
filter_backends = [SearchFilter] # Add search filter
|
||||
search_fields = ['name', 'description'] # Search by name and description
|
||||
permission_classes = [IsAuthenticatedOrReadOnly] # Apply custom permission
|
||||
|
||||
# Retrieve, Update, and Delete a Plant
|
||||
class PlantRetrieveUpdateDestroyAPIView(generics.RetrieveUpdateDestroyAPIView):
|
||||
queryset = Plant.objects.all()
|
||||
serializer_class = PlantSerializer
|
||||
parser_classes = [JSONParser, MultiPartParser, FormParser] # Allow file uploads and form data
|
||||
permission_classes = [IsAuthenticatedOrReadOnly] # Apply custom permission
|
||||
6
plant_catalog/catalog/apps.py
Executable file
6
plant_catalog/catalog/apps.py
Executable file
|
|
@ -0,0 +1,6 @@
|
|||
from django.apps import AppConfig
|
||||
|
||||
|
||||
class CatalogConfig(AppConfig):
|
||||
default_auto_field = 'django.db.models.BigAutoField'
|
||||
name = 'catalog'
|
||||
14
plant_catalog/catalog/models.py
Executable file
14
plant_catalog/catalog/models.py
Executable file
|
|
@ -0,0 +1,14 @@
|
|||
# catalog/models.py
|
||||
|
||||
from django.db import models
|
||||
|
||||
class Plant(models.Model):
|
||||
name = models.CharField(max_length=100)
|
||||
description = models.TextField(null=True, blank=True) # Allow null and blank
|
||||
image = models.ImageField(upload_to='plants/', null=True, blank=True) # Optional image
|
||||
buy_price = models.FloatField(null=True, blank=True) # Allow null for buy price
|
||||
sell_price = models.FloatField(null=True, blank=True) # Allow null for sell price
|
||||
stock = models.IntegerField(default=0) # Default to 0
|
||||
|
||||
def __str__(self):
|
||||
return self.name
|
||||
10
plant_catalog/catalog/permissions.py
Normal file
10
plant_catalog/catalog/permissions.py
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
from rest_framework.permissions import SAFE_METHODS, BasePermission
|
||||
|
||||
class IsAuthenticatedOrReadOnly(BasePermission):
|
||||
"""
|
||||
Allows GET, HEAD, OPTIONS for everyone, but restricts POST, PUT, DELETE to authenticated users.
|
||||
"""
|
||||
def has_permission(self, request, view):
|
||||
if request.method in SAFE_METHODS:
|
||||
return True # Allow read-only access
|
||||
return request.user and request.user.is_authenticated
|
||||
17
plant_catalog/catalog/serializers.py
Executable file
17
plant_catalog/catalog/serializers.py
Executable file
|
|
@ -0,0 +1,17 @@
|
|||
# catalog/serializers.py
|
||||
|
||||
from rest_framework import serializers
|
||||
from .models import Plant
|
||||
|
||||
class PlantSerializer(serializers.ModelSerializer):
|
||||
class Meta:
|
||||
model = Plant
|
||||
fields = ['id', 'name', 'description', 'image', 'buy_price', 'sell_price', 'stock'] # Include all fields
|
||||
extra_kwargs = {
|
||||
'buy_price': {'required': False, 'allow_null': True}, # Allow null for buy price
|
||||
'sell_price': {'required': False, 'allow_null': True}, # Allow null for sell price
|
||||
'image': {'required': False, 'allow_null': True}, # Allow image to be optional
|
||||
'description': {'required': False, 'allow_null': True}, # Optional description
|
||||
}
|
||||
|
||||
|
||||
3
plant_catalog/catalog/tests.py
Executable file
3
plant_catalog/catalog/tests.py
Executable file
|
|
@ -0,0 +1,3 @@
|
|||
from django.test import TestCase
|
||||
|
||||
# Create your tests here.
|
||||
17
plant_catalog/catalog/urls.py
Executable file
17
plant_catalog/catalog/urls.py
Executable file
|
|
@ -0,0 +1,17 @@
|
|||
# catalog/urls.py
|
||||
|
||||
from django.http import HttpResponseRedirect
|
||||
from django.urls import path
|
||||
from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView
|
||||
from .api_views import PlantListCreateAPIView, PlantRetrieveUpdateDestroyAPIView
|
||||
|
||||
urlpatterns = [
|
||||
path('', lambda request: HttpResponseRedirect('/api/plants/')),
|
||||
path('api/plants/', PlantListCreateAPIView.as_view(), name='plant_list_create'), # List and Create
|
||||
path('api/plants/<int:pk>/', PlantRetrieveUpdateDestroyAPIView.as_view(), name='plant_detail_update_delete'), # Retrieve, Update, Delete
|
||||
path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
|
||||
path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
|
||||
]
|
||||
|
||||
|
||||
|
||||
23
plant_catalog/catalog/views.py
Executable file
23
plant_catalog/catalog/views.py
Executable file
|
|
@ -0,0 +1,23 @@
|
|||
# from django.shortcuts import render, get_object_or_404
|
||||
# from .models import Plant
|
||||
|
||||
# def plant_list(request):
|
||||
# plants = Plant.objects.all()
|
||||
# return render(request, 'catalog/plant_list.html', {'plants': plants})
|
||||
|
||||
# def plant_detail(request, pk):
|
||||
# plant = get_object_or_404(Plant, pk=pk)
|
||||
# return render(request, 'catalog/plant_detail.html', {'plant': plant})
|
||||
|
||||
|
||||
# from django.views.generic import ListView, DetailView
|
||||
# from catalog.models import Plant
|
||||
|
||||
# class PlantListView(ListView):
|
||||
# model = Plant
|
||||
# template_name = 'catalog/plant_list.html' # You should have a corresponding template
|
||||
|
||||
# class PlantDetailView(DetailView):
|
||||
# model = Plant
|
||||
# template_name = 'catalog/plant_detail.html' # You should have a corresponding template
|
||||
|
||||
22
plant_catalog/manage.py
Executable file
22
plant_catalog/manage.py
Executable 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', 'plant_catalog.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()
|
||||
0
plant_catalog/plant_catalog/__init__.py
Executable file
0
plant_catalog/plant_catalog/__init__.py
Executable file
16
plant_catalog/plant_catalog/asgi.py
Executable file
16
plant_catalog/plant_catalog/asgi.py
Executable file
|
|
@ -0,0 +1,16 @@
|
|||
"""
|
||||
ASGI config for plant_catalog 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/5.0/howto/deployment/asgi/
|
||||
"""
|
||||
|
||||
import os
|
||||
|
||||
from django.core.asgi import get_asgi_application
|
||||
|
||||
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'plant_catalog.settings')
|
||||
|
||||
application = get_asgi_application()
|
||||
218
plant_catalog/plant_catalog/settings.py
Executable file
218
plant_catalog/plant_catalog/settings.py
Executable file
|
|
@ -0,0 +1,218 @@
|
|||
"""
|
||||
Django settings for plant_catalog project.
|
||||
|
||||
Generated by 'django-admin startproject' using Django 5.0.8.
|
||||
|
||||
For more information on this file, see
|
||||
https://docs.djangoproject.com/en/5.0/topics/settings/
|
||||
|
||||
For the full list of settings and their values, see
|
||||
https://docs.djangoproject.com/en/5.0/ref/settings/
|
||||
"""
|
||||
|
||||
import os
|
||||
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/5.0/howto/deployment/checklist/
|
||||
|
||||
# SECURITY WARNING: keep the secret key used in production secret!
|
||||
SECRET_KEY = 'django-insecure-(e9sx(r=75hv%xni#rcm4)0&67c34+her^!%7dqlghem1=l0lc'
|
||||
|
||||
# SECURITY WARNING: don't run with debug turned on in production!
|
||||
DEBUG = False
|
||||
|
||||
ALLOWED_HOSTS = ['gonzalohd.eu', 'plantsapi.gonzalohd.eu', 'localhost', '192.168.1.139', '127.0.0.1']
|
||||
# ALLOWED_HOSTS = ['*']
|
||||
|
||||
|
||||
CSRF_TRUSTED_ORIGINS = [
|
||||
"https://succulentspectrum.gonzalohd.eu",
|
||||
"https://plantsapi.gonzalohd.eu",
|
||||
"http://localhost:5173", # local development URL
|
||||
]
|
||||
|
||||
CORS_ALLOW_HEADERS = [
|
||||
'authorization',
|
||||
'content-type',
|
||||
'accept',
|
||||
'origin',
|
||||
'x-requested-with',
|
||||
'user-agent',
|
||||
'accept-language',
|
||||
]
|
||||
|
||||
|
||||
|
||||
# Application definition
|
||||
|
||||
INSTALLED_APPS = [
|
||||
'django.contrib.admin',
|
||||
'django.contrib.auth',
|
||||
'django.contrib.contenttypes',
|
||||
'django.contrib.sessions',
|
||||
'django.contrib.messages',
|
||||
'django.contrib.staticfiles',
|
||||
'rest_framework',
|
||||
'catalog',
|
||||
'corsheaders',
|
||||
]
|
||||
|
||||
MIDDLEWARE = [
|
||||
'corsheaders.middleware.CorsMiddleware',
|
||||
|
||||
'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',
|
||||
]
|
||||
|
||||
|
||||
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
|
||||
USE_X_FORWARDED_HOST = True
|
||||
|
||||
|
||||
CORS_ALLOW_ALL_ORIGINS = True # Allow all origins for development
|
||||
|
||||
ROOT_URLCONF = 'plant_catalog.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',
|
||||
],
|
||||
},
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
REST_FRAMEWORK = {
|
||||
'DEFAULT_RENDERER_CLASSES': (
|
||||
'rest_framework.renderers.JSONRenderer',
|
||||
'rest_framework.renderers.BrowsableAPIRenderer', # Enable browsable API
|
||||
),
|
||||
'DEFAULT_PARSER_CLASSES': (
|
||||
'rest_framework.parsers.JSONParser',
|
||||
'rest_framework.parsers.FormParser',
|
||||
'rest_framework.parsers.MultiPartParser',
|
||||
),
|
||||
'DEFAULT_AUTHENTICATION_CLASSES': (
|
||||
'rest_framework_simplejwt.authentication.JWTAuthentication',
|
||||
),
|
||||
'DEFAULT_PERMISSION_CLASSES': (
|
||||
'rest_framework.permissions.IsAuthenticated',
|
||||
),
|
||||
}
|
||||
|
||||
WSGI_APPLICATION = 'plant_catalog.wsgi.application'
|
||||
|
||||
|
||||
# Database
|
||||
# https://docs.djangoproject.com/en/5.0/ref/settings/#databases
|
||||
|
||||
DATABASES = {
|
||||
'default': {
|
||||
'ENGINE': 'django.db.backends.mysql',
|
||||
'NAME': 'plant_catalog_db',
|
||||
'USER': 'catalog_user',
|
||||
'PASSWORD': 'secure_password',
|
||||
'HOST': 'localhost',
|
||||
'PORT': '3306',
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
# Password validation
|
||||
# https://docs.djangoproject.com/en/5.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/5.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/5.0/howto/static-files/
|
||||
|
||||
STATIC_URL = '/static/' # This URL will be used in HTML to load static assets
|
||||
# STATIC_ROOT = '/var/www/simple-plant-archive-django/staticfiles' # Path where collectstatic will store files
|
||||
STATIC_ROOT = os.path.join(BASE_DIR.parent, 'staticfiles') # or any other directory
|
||||
|
||||
# Remove or comment out STATICFILES_DIRS in production
|
||||
# STATICFILES_DIRS = [
|
||||
# os.path.join(BASE_DIR, 'static'),
|
||||
# ]
|
||||
|
||||
# Media files (Uploaded content)
|
||||
|
||||
MEDIA_URL = '/media/'# Base URL for media files
|
||||
# MEDIA_ROOT = '/var/www/simple-plant-archive-django/media'
|
||||
MEDIA_ROOT = os.path.join(BASE_DIR.parent, 'media') # Path to store uploaded files
|
||||
# MEDIA_ROOT = '/var/www/simple-plant-archive-django/media'
|
||||
|
||||
# Default primary key field type
|
||||
# https://docs.djangoproject.com/en/5.0/ref/settings/#default-auto-field
|
||||
|
||||
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
|
||||
|
||||
import os
|
||||
|
||||
LOGGING = {
|
||||
'version': 1,
|
||||
'disable_existing_loggers': False,
|
||||
'handlers': {
|
||||
'file': {
|
||||
'level': 'ERROR', # You can set this to 'DEBUG' for more verbose output
|
||||
'class': 'logging.FileHandler',
|
||||
'filename': os.path.join(BASE_DIR, 'django_error.log'),
|
||||
},
|
||||
},
|
||||
'loggers': {
|
||||
'django': {
|
||||
'handlers': ['file'],
|
||||
'level': 'ERROR', # Match this level to the handler level
|
||||
'propagate': True,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
28
plant_catalog/plant_catalog/urls.py
Executable file
28
plant_catalog/plant_catalog/urls.py
Executable file
|
|
@ -0,0 +1,28 @@
|
|||
"""
|
||||
URL configuration for plant_catalog project.
|
||||
|
||||
The `urlpatterns` list routes URLs to views. For more information please see:
|
||||
https://docs.djangoproject.com/en/5.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
|
||||
from django.conf import settings
|
||||
from django.conf.urls.static import static
|
||||
|
||||
urlpatterns = [
|
||||
path('admin/', admin.site.urls),
|
||||
path('', include('catalog.urls')), # Include the app's URLs
|
||||
]
|
||||
|
||||
if settings.DEBUG:
|
||||
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
|
||||
16
plant_catalog/plant_catalog/wsgi.py
Executable file
16
plant_catalog/plant_catalog/wsgi.py
Executable file
|
|
@ -0,0 +1,16 @@
|
|||
"""
|
||||
WSGI config for plant_catalog 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/5.0/howto/deployment/wsgi/
|
||||
"""
|
||||
|
||||
import os
|
||||
|
||||
from django.core.wsgi import get_wsgi_application
|
||||
|
||||
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'plant_catalog.settings')
|
||||
|
||||
application = get_wsgi_application()
|
||||
13
requirements.txt
Executable file
13
requirements.txt
Executable file
|
|
@ -0,0 +1,13 @@
|
|||
asgiref==3.8.1
|
||||
Django==5.0.8
|
||||
django-cors-headers==4.4.0
|
||||
djangorestframework==3.15.2
|
||||
djangorestframework-simplejwt==5.3.1
|
||||
mysqlclient==2.2.4
|
||||
pillow==10.4.0
|
||||
sqlparse==0.5.1
|
||||
|
||||
pip==23.0.1
|
||||
PyJWT==2.10.0
|
||||
setuptools==66.1.1
|
||||
wheel==0.37.0
|
||||
Loading…
Add table
Reference in a new issue