Django Permissioned Forms

0.1 · active · verified Thu Apr 09

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

Install

Imports

Quickstart

To create a permissioned form, subclass either `PermissionedForm` or `PermissionedModelForm`. Define an inner `Meta` class and set `field_permissions` as a dictionary mapping field names to Django permission codenames (e.g., 'app_label.codename'). Instantiate the form by passing the `for_user` keyword argument with a Django user object. Fields for which the user lacks permission will be omitted from the form.

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)

view raw JSON →