Skip to content

Commit 18433d0

Browse files
Add, correct or fix form validation
1 parent 44778ab commit 18433d0

4 files changed

Lines changed: 49 additions & 6 deletions

File tree

src/shiftings/accounts/forms/user_form.py

Lines changed: 22 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,11 @@
1-
from typing import Any, Dict
1+
from typing import Any, Optional
22

33
from django import forms
4+
from django.contrib.auth.password_validation import get_password_validators, validate_password
45
from django.utils.translation import gettext_lazy as _
56

67
from shiftings.accounts.models import User
8+
from shiftings.settings import AUTH_PASSWORD_VALIDATORS
79

810

911
class UserCreateForm(forms.ModelForm):
@@ -26,11 +28,16 @@ def clean(self) -> Dict[str, Any]:
2628
password = cleaned_data['password']
2729
confirm_password = cleaned_data['confirm_password']
2830
if password != confirm_password:
29-
raise forms.ValidationError(
30-
_('Please enter matching passwords')
31-
)
32-
return cleaned_data
31+
self.add_error('password', _('Please enter matching passwords'))
32+
self.add_error('confirm_password', _('Please enter matching passwords'))
33+
34+
# validate password using Django's built-in validators
35+
try:
36+
validate_password(password, user=None, password_validators=get_password_validators(AUTH_PASSWORD_VALIDATORS))
37+
except forms.ValidationError as e:
38+
self.add_error('password', e)
3339

40+
return cleaned_data
3441

3542
class UserUpdateForm(forms.ModelForm):
3643
class Meta:
@@ -47,3 +54,13 @@ def __init__(self, *args: Any, **kwargs: Any) -> None:
4754
self.fields['first_name'].disabled = True
4855
self.fields['last_name'].disabled = True
4956
self.fields['email'].disabled = True
57+
58+
def clean(self) -> Optional[dict[str, Any]]:
59+
cleaned_data = super().clean()
60+
if hasattr(self.instance, 'ldap_user'):
61+
# if this is an ldap user, ensure that the fields are not changed
62+
if (cleaned_data.get('first_name') != self.instance.first_name or
63+
cleaned_data.get('last_name') != self.instance.last_name or
64+
cleaned_data.get('email') != self.instance.email):
65+
raise forms.ValidationError(_('Cannot change first name, last name or email for LDAP users.'))
66+
return cleaned_data

src/shiftings/mail/forms/mail.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
1+
from typing import Any, Optional
2+
13
from django import forms
24
from django.utils.translation import gettext_lazy as _
35

6+
from shiftings.mail.settings import MAX_ATTACHMENT_SIZE_MB, MAX_TOTAL_ATTACHMENT_SIZE_MB
47
from shiftings.organizations.models import MembershipType, Organization
58
from shiftings.shifts.models import ShiftType
69
from shiftings.utils.fields.date_time import DateTimeFormField
@@ -14,6 +17,19 @@ class MailForm(forms.Form):
1417
def __init__(self, *args, **kwargs):
1518
super().__init__(*args, **kwargs)
1619
self.fields['attachments'].widget.attrs['multiple'] = True
20+
21+
def clean(self) -> dict[str, Any]:
22+
cleaned_data = super().clean()
23+
attachments = self.files.getlist('attachments')
24+
for attachment in attachments:
25+
if attachment.size > MAX_ATTACHMENT_SIZE_MB * 1024 * 1024: # Convert MB to bytes
26+
self.add_error('attachments', _('Each attachment must be smaller than 10 MB.'))
27+
break
28+
29+
if sum(attachment.size for attachment in attachments) > MAX_TOTAL_ATTACHMENT_SIZE_MB * 1024 * 1024:
30+
self.add_error('attachments', _('Total attachment size must be smaller than 25 MB.'))
31+
32+
return cleaned_data
1733

1834

1935
class OrganizationMailForm(MailForm):
@@ -46,3 +62,11 @@ def __init__(self, organization: Organization, *args, **kwargs):
4662
self.organization = organization
4763

4864
self.fields['shift_types'].queryset = organization.shift_types
65+
66+
def clean(self) -> Optional[dict[str, Any]]:
67+
cleaned_data = super().clean()
68+
start = cleaned_data.get('start')
69+
end = cleaned_data.get('end')
70+
if start and end and start > end:
71+
raise forms.ValidationError(_('Start time must be before end time.'))
72+
return cleaned_data

src/shiftings/mail/settings.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
MAX_ATTACHMENT_SIZE_MB : int = 10
2+
MAX_TOTAL_ATTACHMENT_SIZE_MB : int = 25

src/shiftings/shifts/forms/shift.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ def clean(self) -> Dict[str, Any]:
3636
start = cleaned_data.get('start')
3737
end = cleaned_data.get('end')
3838
if start and end and start > end:
39-
self.add_error('end', ValidationError(_('End time must be after start time')))
39+
raise ValidationError(_('End time must be after start time'))
4040

4141
## TODO: raise form error if not valid, but first implement proper error display in template
4242
max_length = timedelta(minutes=settings.MAX_SHIFT_LENGTH_MINUTES)

0 commit comments

Comments
 (0)