diff --git a/babybuddy/forms.py b/babybuddy/forms.py index db96dd2b..14d4495b 100644 --- a/babybuddy/forms.py +++ b/babybuddy/forms.py @@ -1,12 +1,20 @@ # -*- coding: utf-8 -*- from django import forms -from django.contrib.auth.forms import PasswordChangeForm, UserCreationForm from django.contrib.auth import get_user_model +from django.contrib.auth.forms import PasswordChangeForm, UserCreationForm +from django.contrib.auth.models import Group +from django.utils.translation import gettext_lazy as _ from .models import Settings -class UserAddForm(UserCreationForm): +class BabyBuddyUserForm(forms.ModelForm): + is_readonly = forms.BooleanField( + required=False, + label=_("Read only"), + help_text=_("Restricts user to viewing data only."), + ) + class Meta: model = get_user_model() fields = [ @@ -15,29 +23,41 @@ class UserAddForm(UserCreationForm): "last_name", "email", "is_staff", + "is_readonly", "is_active", ] + def __init__(self, *args, **kwargs): + user = kwargs["instance"] + if user: + kwargs["initial"].update( + {"is_readonly": user.groups.filter(name="read_only").exists()} + ) + super(BabyBuddyUserForm, self).__init__(*args, **kwargs) + def save(self, commit=True): - user = super(UserAddForm, self).save(commit=False) - # All Baby Buddy users are superusers. - user.is_superuser = True + user = super(BabyBuddyUserForm, self).save(commit=False) + is_readonly = self.cleaned_data["is_readonly"] + if is_readonly: + user.is_superuser = False + else: + user.is_superuser = True if commit: user.save() + readonly_group = Group.objects.get(name="read_only") + if is_readonly: + user.groups.add(readonly_group.id) + else: + user.groups.remove(readonly_group.id) return user -class UserUpdateForm(forms.ModelForm): - class Meta: - model = get_user_model() - fields = [ - "username", - "first_name", - "last_name", - "email", - "is_staff", - "is_active", - ] +class UserAddForm(BabyBuddyUserForm, UserCreationForm): + pass + + +class UserUpdateForm(BabyBuddyUserForm): + pass class UserForm(forms.ModelForm): diff --git a/babybuddy/templates/babybuddy/user_list.html b/babybuddy/templates/babybuddy/user_list.html index 587756ab..076fed0f 100644 --- a/babybuddy/templates/babybuddy/user_list.html +++ b/babybuddy/templates/babybuddy/user_list.html @@ -1,5 +1,5 @@ {% extends 'babybuddy/page.html' %} -{% load bootstrap i18n widget_tweaks %} +{% load babybuddy_tags bootstrap i18n widget_tweaks %} {% block title %}{% trans "Users" %}{% endblock %} @@ -18,6 +18,7 @@