Skip to content

A bridge between Django and JavaScript for sharing model definitions and validations between backend and frontend.

License

Notifications You must be signed in to change notification settings

engmaryamameen/django-js-model-bridge

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 

History

3 Commits
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Django-JavaScript Model Bridge

A powerful bridge between Django and JavaScript for sharing model definitions and validations between backend and frontend, ensuring consistent validation across your full-stack application.

๐Ÿš€ Features

  • Single Source of Truth: Define validation rules once in Django models
  • Automatic Client-Side Validation: Generate JavaScript validation from Django schemas
  • Real-time Form Validation: Immediate user feedback without server requests
  • API-First Design: Expose validation rules as RESTful endpoints
  • Type Safety: Consistent data types across frontend and backend
  • Comprehensive Demo: Live examples with User and Product models

๐ŸŽฏ Use Cases

  • E-commerce platforms with complex product validation (SKU, pricing, dimensions)
  • User registration systems with business rules (email domains, username restrictions)
  • Data entry applications requiring consistent validation
  • API-first applications with multiple frontend clients
  • Full-stack teams needing synchronized validation logic

โšก Quick Start

Prerequisites

  • Python 3.8+
  • Django 5.2+
  • Modern web browser

Installation

# Clone the repository
git clone https://github.com/engmaryamameen/django-js-model-bridge.git
cd django-js-model-bridge

# Create and activate virtual environment
python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate

# Install dependencies
pip install -r requirements.txt

# Run database migrations
python manage.py migrate

# Start the development server
python manage.py runserver

# Visit http://localhost:8000 to see the demo

๐ŸŽฎ Live Demo

Once the server is running, visit http://localhost:8000 to see:

  • User Registration Form: Email validation, username rules, age restrictions
  • Product Creation Form: SKU validation, pricing rules, dimension constraints
  • API Information: Live schema endpoints and validation testing
  • Real-time Validation: Immediate feedback as you type

๐Ÿ—๏ธ Architecture

Backend (Django)

# models.py
class User(models.Model):
    email = models.EmailField(unique=True)
    username = models.CharField(max_length=150, unique=True)
    # Validation rules defined here

# views.py
class ModelSchemaView(APIView):
    def get(self, request, model_name=None):
        # Expose model schemas as JSON

Frontend (JavaScript)

// Fetch validation rules from Django
const apiClient = new APIClient();
const schemas = await apiClient.getAllSchemas();

// Apply validation in real-time
const validator = new FormValidator(apiClient, User);
await validator.initialize(formElement);

๐Ÿ“š API Endpoints

Endpoint Method Description
/api/ GET API information and available endpoints
/api/schema/ GET Get all model schemas
/api/schema/{model}/ GET Get specific model schema
/api/validate/ POST Validate data against model rules
/api/users/ GET/POST User CRUD operations
/api/products/ GET/POST Product CRUD operations

๐Ÿ”ง Configuration

CORS Settings

# settings.py
CORS_ALLOW_ALL_ORIGINS = True  # Development only
CORS_ALLOWED_ORIGINS = [
    "http://localhost:8000",
    "http://127.0.0.1:8000",
]

Static Files

STATIC_URL = 'static/'
STATICFILES_DIRS = [
    BASE_DIR / 'static',
]

๐Ÿ“– Usage Examples

1. Define Django Model

from django.db import models

class Product(models.Model):
    name = models.CharField(max_length=200, validators=[...])
    sku = models.CharField(max_length=50, unique=True, validators=[...])
    price = models.DecimalField(max_digits=10, decimal_places=2)
    # ... other fields with validation

2. Create API Endpoint

from rest_framework.views import APIView

class ModelSchemaView(APIView):
    def get(self, request, model_name=None):
        if model_name == 'product':
            return Response(ModelSchemaSerializer().to_representation(Product))

3. Use in JavaScript

// Initialize API client
const apiClient = new APIClient();

// Get validation rules
const schemas = await apiClient.getAllSchemas();

// Create form validator
const validator = new FormValidator(apiClient, Product);
await validator.initialize(document.getElementById('product-form'));

๐Ÿงช Testing

# Run Django tests
python manage.py test

# Test API endpoints
curl http://localhost:8000/api/
curl http://localhost:8000/api/schema/

๐Ÿค Contributing

We welcome contributions! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.

Development Setup

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

๐Ÿ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

Acknowledgments

  • Django REST Framework for the excellent API framework
  • Django CORS Headers for handling cross-origin requests
  • The Django community for inspiration and best practices

๐Ÿ“ž Support

If you have any questions or need help:

  • Open an issue
  • Check the demo for working examples
  • Review the code comments for implementation details

Made with โค๏ธ by Maryam Ameen

โญ If this project helps you, please give it a star!

About

A bridge between Django and JavaScript for sharing model definitions and validations between backend and frontend.

Resources

License

Code of conduct

Contributing

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published