A while back I was working on a document management feature. Users could create documents, but naturally they should only be able to edit or delete their own. Managers, on the other hand, needed broader access so they could edit any document within their department. And then there were reports that had to be publicly readable by anyone, even without logging in. Django’s built-in permissions work well when things are global, like saying “managers can edit all documents”. But the moment you step into real-world rules like “this user can only edit their own documents” or “this specific person can access this one record”, you end up writing custom checks everywhere. It quickly becomes repetitive and a bit fragile. I kept running into the same problems, so I wanted something cleaner and reusable for: - Per-object permissions for individual records - Automatic ownership rules (users managing their own content) - Public access for specific endpoints without authentication - DRF action mapping so permissions are consistent across endpoints - Permission caching to avoid unnecessary database hits on every request Yes, django-guardian exists – but it's heavy and requires extra wiring for DRF. I wanted something lighter, DRF‑native, and drop‑dead simple. That is what led me to build django-user-permissions, a lightweight package that plugs into Django REST Framework. It gives you a simple mixin for viewsets, a way to attach permissions directly to objects, and a few controls for ownership and public access. The idea was not to build another heavy role system, but to fill in the gaps Django leaves at the object level. If you have ever had to implement “edit only your own posts” or “share a single private document with someone”, you probably know how quickly this logic spreads across a codebase. This is just my attempt to keep that part of Django a bit more manageable. 📦 PyPI: [https://lnkd.in/gR63kZdB) 💻 GitHub: https://lnkd.in/geSY5Mfj pip install django-user-permissions #Django #DRF #Python #OpenSource #Permissions
django-user-permissions for Django REST Framework
More Relevant Posts
-
If you're already comfortable building APIs with Django REST Framework (DRF), it's time to move beyond the basics and explore more powerful patterns that can make your APIs scalable, secure, and production-ready. 🔍 1. Custom Pagination Strategies Default pagination is great—but advanced systems often require cursor-based or dynamic pagination for better performance with large datasets. ⚙️ 2. Optimizing Querysets with select_related & prefetch_related Avoid the dreaded N+1 query problem. Efficient queryset optimization can drastically improve API response times. 🔐 3. Fine-Grained Permissions & Role-Based Access Control (RBAC) Go beyond IsAuthenticated. Build custom permission classes to control access at object-level granularity. 🧩 4. Serializer Performance Tweaks Use SerializerMethodField wisely, and consider values() or only() for lightweight responses when full serialization isn't needed. 🔄 5. Throttling & Rate Limiting Protect your APIs from abuse by implementing custom throttling strategies tailored to different user roles. 📦 6. API Versioning Strategies Maintain backward compatibility with URL-based or header-based versioning—crucial for long-term projects. 🧪 7. Advanced Testing with APITestCase Ensure robustness with comprehensive unit and integration tests. Mock external services and validate edge cases. ⚡ 8. Asynchronous Tasks with Celery Offload heavy operations (emails, reports, background processing) to task queues for better performance and user experience. 💡 Pro Tip: Combine DRF with tools like Redis caching and database indexing to unlock serious performance gains. 🔥 Mastering these advanced concepts can transform your API from functional to exceptional. What advanced DRF techniques are you currently exploring? Let’s discuss 👇 #Django #Python #BackendDevelopment #RESTAPI #SoftwareEngineering #WebDevelopment
To view or add a comment, sign in
-
Day 95 – Django Model Relationships, Admin Integration & Media Handling Today I worked on building dynamic Course and Teacher management in Django by connecting frontend and backend with database-driven content. 🔹 Created a new Course Details page with navigation integration using templates, views, and URL routing. 🔹 Built a Details model with: • Course_name (CharField) • Course_dtls (TextField) Learned the importance of: ✔ null=True ✔ blank=True ✔ max_length ✔ Difference between CharField and TextField 🔹 Performed database migration using: makemigrations migrate 🔹 Registered models in Django Admin for easy backend management. 🔹 Fetched database content dynamically to the frontend using: Details.objects.all() and displayed it with Django template for-loops. 🔹 Created a second model: Teacher Fields included: • Teach_name • Course_name (ForeignKey with Details) • Teach_img (ImageField) This helped me understand: ✔ ForeignKey relationships ✔ on_delete=models.CASCADE ✔ Connecting two models in Django 🔹 Installed Pillow for image handling and configured: MEDIA_ROOT MEDIA_URL Also updated project urls.py for serving media files properly. 🔹 Successfully fetched teacher images from backend to frontend using: {{ i.Teach_img.url }} Today’s learning gave me a strong understanding of Django model relationships, admin panel usage, migrations, and media file management. Step by step, backend development is becoming more practical and exciting! 💻 #Django #Python #WebDevelopment #BackendDevelopment #FullStackDevelopment #DjangoDeveloper #SoftwareDevelopment #PythonDeveloper #DatabaseManagement
To view or add a comment, sign in
-
After deploying the initial version of my inventory management system, I’ve been working on expanding the backend using Django REST Framework. What I’ve added: • Integrated Django REST Framework into the existing project • Set up versioned API routing → /api/v1/ • Built serializers for core models: Device DeviceRequest Assignment • Implemented nested serialization so assignment responses include full device details • Created read-only APIs using ViewSets: DeviceViewSet (list, retrieve) AssignmentViewSet (list, retrieve) • Wired everything using DefaultRouter • Tested endpoints like /api/v1/devices/ — returning structured JSON responses What I focused on this time: • Structuring APIs cleanly on top of an existing deployed system • Understanding how DRF handles serialization and routing internally • Keeping APIs controlled (only exposing what’s needed) • Improving query performance using select_related Next phase: • Add action-based endpoints (approve requests, return devices, extend duration) • Connect ViewSets with service layer logic • Introduce permissions and validation • Move towards a more production-ready API design Continuing to build this as a full backend system with real-world workflows (request → approve → assign → return). #Django #DRF #BackendDevelopment #Python #WebDevelopment #APIs
To view or add a comment, sign in
-
Is the "Boilerplate" argument against Django Ninja finally dead? 🐍🥷 I’ve been diving deep into the DRF vs. Django Ninja debate lately. For years, the community pointed to a specific deal-breaker: Boilerplate. I recently revisited a famous 2024 article from Loopwerk that essentially "killed" Ninja for four reasons: 1️⃣ Lack of ViewSets: Writing 30+ lines for basic CRUD that DRF does in 4. 2️⃣ Scattered Logic: Permissions and filters weren't centralized. 3️⃣ Messy Nested Resources: Handling child models (like Characters in a Campaign) was a manual nightmare. 4️⃣ Manual Error Handling: Constantly writing get_object_or_404. But here’s the thing: It’s 2026, and that article is now a history lesson, not a roadmap. With the maturity of Django Ninja Extra and Ninja CRUD, almost all those "weak points" are solved. You now get: ✅ Class-Based Controllers that centralize permissions. ✅ ModelViewSets that handle CRUD in the same 4 lines of code. ✅ Global Exception Handlers that catch 404s and validation errors automatically. The Reality Check: We get the speed of FastAPI/Pydantic, the power of the Django ORM, and the DX of DRF ViewSets—all in one stack. So my question to the backend community: If the "boilerplate" gap is gone, and the performance gap is huge (Pydantic is significantly faster than DRF serializers), why isn't Ninja the absolute default yet? Is it just "Enterprise Inertia," or is there still a secret sauce in DRF that we’re missing? 🧐 #Django #Python #BackendDevelopment #DjangoNinja #WebDev #APIDevelopment
To view or add a comment, sign in
-
-
Django's Project Structurre: Most beginners get confused by Django’s project structure. It looks complex at first—but it’s actually very well organized 👇 Here’s a simple breakdown: 📁 project/ ┣ 📄 manage.py ┣ 📁 project/ ┃ ┣ 📄 settings.py ┃ ┣ 📄 urls.py ┃ ┣ 📄 asgi.py / wsgi.py ┃ ┗ 📄 init.py ┗ 📁 app/ ┣ 📄 models.py ┣ 📄 views.py ┣ 📄 urls.py ┣ 📄 admin.py ┗ 📄 tests.py 💡 What each part does: • manage.py → Run server, migrations, commands • settings.py → Project configuration • urls.py → Routing system • models.py → Database structure • views.py → Business logic • admin.py → Admin panel setup 💡 Why this structure matters: ✔ Clean and scalable code ✔ Easy team collaboration ✔ Built-in best practices Once you understand this, Django becomes much easier 🚀 Are you currently learning Django or FastAPI? 👇 #Django #Python #BackendDevelopment #WebDevelopment #LearnToCode #FastAPI
To view or add a comment, sign in
-
-
Choosing the Right Django REST Framework View — A Simple Way to Think When building APIs with Django REST Framework, one question always comes up: 👉 “Which view type should I use?” Here’s the simple way I approach it 👇 🔹 Function-Based Views (@api_view) I use this when the requirement is custom and not CRUD. Example: Sending OTP, triggering a background task, or calling an external API. ➡️ Best for: Small, one-purpose logic where I need full control. 🔹 Class-Based Views (APIView) I choose this when the logic becomes structured and multi-step. Example: File upload → validation → processing → response. ➡️ Best for: Complex workflows that need clean and reusable code. 🔹 Generic Views / ViewSets My go-to for standard CRUD operations. Example: Managing users, expenses, or documents. ➡️ Best for: Saving time using built-in functionality. 💡 My decision logic: CRUD → ViewSets Simple custom logic → Function-Based Complex workflow → APIView This mindset helps me: ✔ Write cleaner code ✔ Avoid over-engineering ✔ Build scalable APIs faster How do you decide which view to use? 🤔 #Django #DjangoRestFramework #Python #WebDevelopment #Remote
To view or add a comment, sign in
-
-
Excited to share something I’ve been working on! I’ve officially published my first Django utility package on PyPI: django-migration-testgen (v0.1.0). As a developer, I’ve always felt that Django migrations are powerful but often under-tested. In real-world projects, especially in large teams and production systems, migrations can silently break things if not properly validated. That’s where this tool comes in. What does it do? It automatically scans your Django apps and generates ready-to-use test files for your migration files, allowing you to confidently verify schema changes, both forward and backward. Why I built this: - Writing migration tests manually is repetitive and often skipped - Migration issues can break production deployments - CI pipelines should validate schema evolution, not just code Key Features: - Auto-discovers all migration files across apps - Generates structured test files per migration - Uses Django’s MigrationExecutor for real execution testing - Supports forward and rollback testing - Dry-run, force overwrite, and custom output directory support - Easy integration into CI/CD pipelines Install & try it: ```bash pip install django-migration-testgen ``` Then just run: ```bash python manage.py generate_migration_tests ``` My goal with this project is simple: make migration testing effortless, scalable, and reliable for Django developers. This is just v0.1.0, and I’m planning to improve it further with smarter test generation, better customization, performance optimizations, and community feedback. If you’re working with Django, I’d love for you to try it out and share your thoughts. Open to feedback, suggestions, and contributions. #Django #Python #OpenSource #SoftwareEngineering #BackendDevelopment #CI #DevOps #Testing #Programming
To view or add a comment, sign in
-
Your Django endpoint is slow. There are no errors, and nothing obvious stands out in the logs. Even average response times can look fine. But one request is quietly running hundreds of small queries and dragging everything down. That’s what makes this hard to spot. In this post, Jaume Boguñá shows how to trace a slow request with AppSignal and fix it once and for all👇 https://lnkd.in/e-6iCZZt
To view or add a comment, sign in
-
🚀 Master RESTful APIs: From Zero to Production API design is one of the most critical skills for any backend developer, yet it’s easy to get the "rules" tangled up. Whether you are working with Python, Flask, or any other framework, these core principles remain the same. I’ve put together a comprehensive breakdown of the RESTful API Masterclass cheat sheet. Here is what you need to know to build professional-grade interfaces: 🔹 The Anatomy of REST: It’s not just a library; it’s an architectural style based on Representational State Transfer. 🔹 Verbs matter: Use GET for reading, POST for creating, PUT for full replacements, and PATCH for partial updates. 🔹 Statelessness is key: Every request must contain all the information the server needs—no "guessing" based on previous interactions. 🔹 Clean URLs: Use plural nouns (/books) instead of verbs (/getBooks). Keep nesting shallow to stay readable. 🔹 Security: Transition from simple API Keys for server-to-server talk to JWT (JSON Web Tokens) for modern, scalable auth. Pro-Tip from the guide: Always keep your v1 running while launching v2. Never make breaking changes without versioning!. Check out the full cheat sheet attached below for a deep dive into status codes and Flask implementation. ⬇️ #Python #Flask #WebDevelopment #API #Backend #CodingTips #RESTAPI
To view or add a comment, sign in
-
Understanding Django Signals — Automating Actions Behind the Scenes 𝗪𝗵𝗮𝘁 𝗮𝗿𝗲 𝗗𝗷𝗮𝗻𝗴𝗼 𝗦𝗶𝗴𝗻𝗮𝗹𝘀? Signals let different parts of your app react to events without tightly coupling code. For example, when a user registers, you can automatically send a welcome email — all without adding email logic inside the registration view. How it works: Define a signal handler — a Python function that runs when the event occurs. from django.dispatch import receiver from django.db.models.signals import post_save from django.contrib.auth import get_user_model User = get_user_model() @receiver(post_save, sender=User) def send_welcome_email(sender, instance, created, **kwargs): if created: # send email logic here print(f"Welcome email sent to {instance.email}") Connect it to a signal — here we used post_save on the User model. Triggered automatically whenever the event occurs (e.g., new user created). Why use signals: • Keeps your code modular — registration logic doesn’t need to know about emails. • Handles side effects cleanly — emails, notifications, analytics, logging. • Scales well — add new handlers without touching core logic.
To view or add a comment, sign in
More from this author
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development
does it work similar as guardian?