1
0
mirror of https://github.com/netbox-community/netbox.git synced 2024-05-10 07:54:54 +00:00

Introduce restrict_form_fields() to automatically restrict field querysets based on user

This commit is contained in:
Jeremy Stretch
2020-06-26 13:59:53 -04:00
parent 8412f9481c
commit edc65a6a34
2 changed files with 14 additions and 1 deletions

View File

@ -15,6 +15,7 @@ from django.forms import BoundField
from django.forms.models import fields_for_model
from django.urls import reverse
from utilities.querysets import RestrictedQuerySet
from .choices import ColorChoices, unpack_grouped_choices
from .validators import EnhancedURLValidator
@ -138,6 +139,16 @@ def form_from_model(model, fields):
return type('FormFromModel', (forms.Form,), form_fields)
def restrict_form_fields(form, user, action='view'):
"""
Restrict all form fields which reference a RestrictedQuerySet. This ensures that users see only permitted objects
as available choices.
"""
for field in form.fields.values():
if hasattr(field, 'queryset') and issubclass(field.queryset.__class__, RestrictedQuerySet):
field.queryset = field.queryset.restrict(user, action)
#
# Widgets
#