Skip to content

Commit

Permalink
Read-only form with correct perm (#393)
Browse files Browse the repository at this point in the history
  • Loading branch information
SebCorbin committed Apr 29, 2020
1 parent 540ead3 commit 1de764a
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 6 deletions.
17 changes: 13 additions & 4 deletions constance/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,10 +97,17 @@ def get_values():
class ConstanceForm(forms.Form):
version = forms.CharField(widget=forms.HiddenInput)

def __init__(self, initial, *args, **kwargs):
def __init__(self, initial, request=None, *args, **kwargs):
super().__init__(*args, initial=initial, **kwargs)
version_hash = hashlib.md5()

only_view = request and not request.user.has_perm('constance.change_config')
if only_view:
messages.warning(
request,
_("You don't have permission to change these values"),
)

for name, options in settings.CONFIG.items():
default = options[0]
if len(options) == 3:
Expand All @@ -123,6 +130,8 @@ def __init__(self, initial, *args, **kwargs):
% {'config_type': config_type,
'name': name})
field_class, kwargs = FIELDS[config_type]
if only_view:
kwargs['disabled'] = True
self.fields[name] = field_class(label=name, **kwargs)

version_hash.update(smart_bytes(initial.get(name, '')))
Expand Down Expand Up @@ -216,12 +225,12 @@ def get_changelist_form(self, request):

@csrf_protect_m
def changelist_view(self, request, extra_context=None):
if not self.has_change_permission(request, None):
if not self.has_view_or_change_permission(request):
raise PermissionDenied
initial = get_values()
form_cls = self.get_changelist_form(request)
form = form_cls(initial=initial)
if request.method == 'POST':
form = form_cls(initial=initial, request=request)
if request.method == 'POST' and request.user.has_perm('constance.change_config'):
form = form_cls(
data=request.POST, files=request.FILES, initial=initial
)
Expand Down
10 changes: 8 additions & 2 deletions constance/apps.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,13 @@ def create_perm(self, using=None, *args, **kwargs):
model='config',
)

permission, created = Permission.objects.using(using).get_or_create(
Permission.objects.using(using).get_or_create(
content_type=content_type,
codename='change_config',
defaults={'name': 'Can change config'})
defaults={'name': 'Can change config'},
)
Permission.objects.using(using).get_or_create(
content_type=content_type,
codename='view_config',
defaults={'name': 'Can view config'},
)

0 comments on commit 1de764a

Please sign in to comment.