Compare commits

..

No commits in common. "54e0c2b793500177ed11cd824d65660c095d618c" and "25cc8f959d3a845c2acd3b52804da0dfc63a5ad5" have entirely different histories.

20 changed files with 1 additions and 460 deletions

24
.gitignore vendored
View file

@ -1,24 +0,0 @@
# 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 Executable file → Normal file
View file

2
README.md Executable file → Normal file
View file

@ -1,2 +1,2 @@
# simple-plant-archive-django # simple-plant-archive-django
Django-based rest api for building a customer-oriented product catalog with archiving features. Django-based app for building a customer-oriented product catalog with archiving features.

View file

@ -1,7 +0,0 @@
from django.contrib import admin
from .models import Plant
@admin.register(Plant)
class PlantAdmin(admin.ModelAdmin):
list_display = ('name', 'image')
search_fields = ('name',)

View file

@ -1,25 +0,0 @@
# 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

View file

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

View file

@ -1,14 +0,0 @@
# 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

View file

@ -1,10 +0,0 @@
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

View file

@ -1,17 +0,0 @@
# 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
}

View file

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

View file

@ -1,17 +0,0 @@
# 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'),
]

View file

@ -1,23 +0,0 @@
# 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

View file

@ -1,22 +0,0 @@
#!/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()

View file

@ -1,16 +0,0 @@
"""
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()

View file

@ -1,218 +0,0 @@
"""
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,
},
},
}

View file

@ -1,28 +0,0 @@
"""
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)

View file

@ -1,16 +0,0 @@
"""
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()

View file

@ -1,13 +0,0 @@
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