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):
is_readonly = forms.BooleanField(
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-08 04:29:06 +00:00
"is_readonly",
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(
{"is_readonly": user.groups.filter(name="read_only").exists()}
)
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)
is_readonly = self.cleaned_data["is_readonly"]
if is_readonly:
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")
if is_readonly:
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",
]