Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/codermungan/djangoessentials
DjangoEssentials is a Python library designed to streamline and enhance the development process of Django applications. It offers a collection of commonly used Django models and deployment settings, encapsulating repetitive patterns and configurations into a reusable package.
https://github.com/codermungan/djangoessentials
django django-application django-framework django-library django-rest-framework library python python-library
Last synced: about 12 hours ago
JSON representation
DjangoEssentials is a Python library designed to streamline and enhance the development process of Django applications. It offers a collection of commonly used Django models and deployment settings, encapsulating repetitive patterns and configurations into a reusable package.
- Host: GitHub
- URL: https://github.com/codermungan/djangoessentials
- Owner: CoderMungan
- License: mit
- Created: 2024-03-18T15:23:06.000Z (11 months ago)
- Default Branch: main
- Last Pushed: 2025-01-27T10:47:34.000Z (16 days ago)
- Last Synced: 2025-01-27T11:15:50.581Z (16 days ago)
- Topics: django, django-application, django-framework, django-library, django-rest-framework, library, python, python-library
- Language: Python
- Homepage: https://pypi.org/project/DjangoEssentials/
- Size: 24.4 KB
- Stars: 12
- Watchers: 1
- Forks: 2
- Open Issues: 4
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
**DjangoEssentials**
[Join Our Community - Kampus](https://discord.gg/kampus)
**DjangoEssentials** is a Python library designed to streamline and simplify the development of Django applications. This library supports modern software development approaches, such as the **repository-service pattern**, and provides a more modular structure by preventing code repetition. Additionally, it includes essential features such as **model management, data access, and Amazon S3 storage integration**.
**π Features**
**1οΈβ£ Repository-Service Pattern**
β’ **BaseRepository:** A base repository class that manages CRUD operations for Django models.
β’ **BaseService:** A service layer that utilizes repositories to manage business logic and reduce code duplication.
**2οΈβ£ Model Utilities**
β’ **TimeBasedStampModel:** An abstract model class that automatically tracks **creation, update, and deletion timestamps**.
**3οΈβ£ Amazon S3 Storage Integration**
β’ **MyS3Storage:** A custom storage class for **handling media files with Amazon S3** in Django applications.
**π₯ Installation**
Install the library using pip:
```python
pip install DjangoEssentials
```**π Usage**
**1οΈβ£ Using the Repository-Service Pattern**
This pattern separates the **data access layer** from the **business logic layer**, making Django applications cleaner and more maintainable.
**π Model Example**
Letβs create a **simple Django model** using TimeBasedStampModel:
```python
from django.db import models
from djangoessentials import TimeBasedStampModelclass Product(TimeBasedStampModel):
name = models.CharField(max_length=255)
description = models.TextField()
price = models.DecimalField(max_digits=10, decimal_places=2)
stock = models.PositiveIntegerField(default=0)
```**π Repository Layer**
The repository interacts with Django models and manages database operations.
```python
from djangoessentials.repository import BaseRepository
from myapp.models import Productclass ProductRepository(BaseRepository[Product]):
def __init__(self):
super().__init__(Product)
```**π Service Layer**
The service layer uses the repository to manage business logic and reduce code duplication.
```python
from djangoessentials.service import BaseService
from myapp.repositories import ProductRepositoryclass ProductService(BaseService[ProductRepository]):
def __init__(self):
super().__init__(ProductRepository())def get_available_products(self):
return self._repository.filter(stock__gt=0)
```**π Serializer for DRF**
To expose this model via an API, letβs create a serializer.
```python
from rest_framework import serializers
from myapp.models import Productclass ProductSerializer(serializers.ModelSerializer):
class Meta:
model = Product
fields = '__all__'
```**π ViewSet for Django REST Framework**
To expose the service through an API, we can use **ModelViewSet**.
```python
from rest_framework import viewsets
from myapp.services import ProductService
from myapp.serializers import ProductSerializerclass ProductViewSet(viewsets.ModelViewSet):
serializer_class = ProductSerializer
queryset = ProductService().get_all()
def get_queryset(self):
"""
Optionally filter the queryset based on stock availability.
"""
service = ProductService()
available_only = self.request.query_params.get('available_only', None)
if available_only:
return service.get_available_products()
return service.get_all()
```**π Register the ViewSet in Djangoβs Router**
To enable API endpoints, register the viewset in urls.py.
```python
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from myapp.views import ProductViewSetrouter = DefaultRouter()
router.register(r'products', ProductViewSet)urlpatterns = [
path('api/', include(router.urls)),
]
```**2οΈβ£ Using TimeBasedStampModel**
To add automatic **created_at, updated_at, and deleted_at** fields to your model:
```python
from django.db import models
from djangoessentials import TimeBasedStampModelclass YourModel(TimeBasedStampModel):
name = models.CharField(max_length=255)
# Add your custom fields here
```This model **automatically tracks timestamps** for each record.
**3οΈβ£ Amazon S3 Storage Integration**
To use **Amazon S3 as the media storage solution**, configure your Django project as follows.
**π Add to settings.py**
```python
import osUSE_S3 = True
if USE_S3:
AWS_ACCESS_KEY_ID = os.getenv("AWS_ACCESS_KEY_ID")
AWS_SECRET_ACCESS_KEY = os.getenv("AWS_SECRET_ACCESS_KEY")
AWS_STORAGE_BUCKET_NAME = os.getenv("AWS_STORAGE_BUCKET_NAME")
AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com'
AWS_S3_OBJECT_PARAMETERS = {'CacheControl': 'max-age=86400'}PUBLIC_MEDIA_LOCATION = 'media'
MEDIA_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{PUBLIC_MEDIA_LOCATION}/'
else:
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')STATIC_URL = 'static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static/')]
```**π Use in a Model**
```python
from django.db import models
from djangoessentials import MyS3Storageclass MyModel(models.Model):
document = models.FileField(upload_to='documents/', storage=MyS3Storage)
```This setup ensures that files are **automatically uploaded to Amazon S3**.
**π― Advanced Usage**
DjangoEssentials is designed to grow with the communityβs needs. Over time, more utilities and helpers will be added to **optimize Django development workflows**.
**π€ Contributing**
We welcome community contributions! If youβd like to add new features, improve documentation, or report bugs, follow these steps:
1. **Fork the repository.**
2. **Create a feature branch:**
```python
git checkout -b feature/AmazingFeature
```3. **Commit your changes:**
```python
git commit -am "Add some AmazingFeature"
```4. **Push to the branch:**
```python
git push origin feature/AmazingFeature
```5. **Open a Pull Request.**
**π© Contact**
For questions or further information, feel free to contact us:
π§ [**[email protected]**](mailto:[email protected])