Django Permissioned Forms
Django extension for creating forms that vary according to user permissions. It allows you to define forms where certain fields are shown or omitted based on the user's permissions. This library is currently at version 0.1 and has an active development cadence.
Warnings
- breaking As this library is at version 0.1, the API is still considered unstable. Future minor or major versions may introduce breaking changes without extensive deprecation cycles. Users should pin exact versions and review release notes carefully for upgrades.
- gotcha Incorrect configuration of Django's native permission system (e.g., missing permissions, misnamed codenames, or improper `AUTHENTICATION_BACKENDS`) can lead to fields being unexpectedly hidden or shown. Ensure your permissions are correctly defined and applied to users/groups.
- gotcha When integrating `PermissionedForm` or `PermissionedModelForm` with another custom base form class that defines its own metaclass, direct multiple inheritance might fail. A custom metaclass inheriting from both `PermissionedFormMetaclass` and the other form's metaclass may be required.
Install
-
pip install django-permissionedforms
Imports
- PermissionedForm
from permissionedforms import PermissionedForm
- PermissionedModelForm
from permissionedforms import PermissionedModelForm
Quickstart
from django import forms
from permissionedforms import PermissionedForm, PermissionedModelForm
# Example 1: Basic Form
class PersonForm(PermissionedForm):
first_name = forms.CharField(max_length=100)
last_name = forms.CharField(max_length=100)
class Meta:
field_permissions = {
'last_name': 'myapp.change_last_name_field'
}
# Example 2: Model Form
# from django.db import models
# class Country(models.Model):
# name = models.CharField(max_length=100)
# description = models.TextField(blank=True)
# class Meta:
# app_label = 'myapp'
# permissions = [('change_country_description', 'Can change country description')]
# class CountryForm(PermissionedModelForm):
# class Meta:
# model = Country
# fields = ['name', 'description']
# field_permissions = {
# 'description': 'myapp.change_country_description'
# }
# Usage in a view (assuming 'request' is an HttpRequest object)
# user = request.user # A Django User object
# form = PersonForm(for_user=user)
# if form.is_valid():
# pass
# model_instance = Country.objects.first() # or create one
# model_form = CountryForm(instance=model_instance, for_user=user)