mybuddy/babybuddy/forms.py

84 lines
2.2 KiB
Python
Raw Normal View History

2017-11-11 22:27:42 +00:00
# -*- coding: utf-8 -*-
from django import forms
from django.contrib.auth import get_user_model
2023-02-08 04:29:06 +00:00
from django.contrib.auth.forms import PasswordChangeForm, UserCreationForm
from django.contrib.auth.models import Group
from django.utils.translation import gettext_lazy as _
2017-11-11 22:27:42 +00:00
from .models import Settings
2023-02-08 04:29:06 +00:00
class BabyBuddyUserForm(forms.ModelForm):
2023-02-09 03:33:22 +00:00
is_read_only = forms.BooleanField(
2023-02-08 04:29:06 +00:00
required=False,
label=_("Read only"),
help_text=_("Restricts user to viewing data only."),
)
class Meta:
model = get_user_model()
2022-02-10 00:00:30 +00:00
fields = [
"username",
"first_name",
"last_name",
"email",
"is_staff",
2023-02-09 03:33:22 +00:00
"is_read_only",
2022-02-10 00:00:30 +00:00
"is_active",
]
2023-02-08 04:29:06 +00:00
def __init__(self, *args, **kwargs):
user = kwargs["instance"]
if user:
kwargs["initial"].update(
2023-02-09 03:33:22 +00:00
{"is_read_only": user.groups.filter(name="read_only").exists()}
2023-02-08 04:29:06 +00:00
)
super(BabyBuddyUserForm, self).__init__(*args, **kwargs)
def save(self, commit=True):
2023-02-08 04:29:06 +00:00
user = super(BabyBuddyUserForm, self).save(commit=False)
2023-02-09 03:33:22 +00:00
is_read_only = self.cleaned_data["is_read_only"]
if is_read_only:
2023-02-08 04:29:06 +00:00
user.is_superuser = False
else:
user.is_superuser = True
if commit:
user.save()
2023-02-08 04:29:06 +00:00
readonly_group = Group.objects.get(name="read_only")
2023-02-09 03:33:22 +00:00
if is_read_only:
2023-02-08 04:29:06 +00:00
user.groups.add(readonly_group.id)
else:
user.groups.remove(readonly_group.id)
return user
2023-02-08 04:29:06 +00:00
class UserAddForm(BabyBuddyUserForm, UserCreationForm):
pass
class UserUpdateForm(BabyBuddyUserForm):
pass
2017-11-11 22:27:42 +00:00
class UserForm(forms.ModelForm):
class Meta:
model = get_user_model()
2022-02-10 00:00:30 +00:00
fields = ["first_name", "last_name", "email"]
2017-11-11 22:27:42 +00:00
2017-12-02 21:20:15 +00:00
class UserPasswordForm(PasswordChangeForm):
class Meta:
2022-02-10 00:00:30 +00:00
fields = ["old_password", "new_password1", "new_password2"]
2017-12-02 21:20:15 +00:00
2017-11-11 22:27:42 +00:00
class UserSettingsForm(forms.ModelForm):
class Meta:
model = Settings
fields = [
2022-02-10 00:00:30 +00:00
"dashboard_refresh_rate",
"dashboard_hide_empty",
"dashboard_hide_age",
"language",
"timezone",
]