79 lines
3.2 KiB
Python
79 lines
3.2 KiB
Python
from django import forms
|
||
from django.utils import timezone
|
||
|
||
from .models import StressEntry
|
||
|
||
SYMPTOMS = (
|
||
('tension', 'Tension'), ('headache', 'Headache'),
|
||
('fatigue', 'Fatigue'), ('restlessness', 'Restlessness'),
|
||
)
|
||
|
||
|
||
def normalize_tags(value):
|
||
if not isinstance(value, list) or len(value) > 12:
|
||
raise forms.ValidationError('Use up to 12 tags.')
|
||
tags = []
|
||
for tag in value:
|
||
if not isinstance(tag, str) or not tag.strip() or len(tag.strip()) > 40:
|
||
raise forms.ValidationError('Each tag must be 1–40 characters.')
|
||
name = tag.strip()
|
||
if name.casefold() not in {item.casefold() for item in tags}:
|
||
tags.append(name)
|
||
return tags
|
||
|
||
|
||
def normalize_symptoms(value):
|
||
allowed = {key for key, _ in SYMPTOMS}
|
||
if not isinstance(value, list) or any(item not in allowed for item in value):
|
||
raise forms.ValidationError('Choose known symptoms.')
|
||
return list(dict.fromkeys(value))
|
||
|
||
|
||
class StressEntryForm(forms.ModelForm):
|
||
recorded_at = forms.DateTimeField(
|
||
label='When', input_formats=['%Y-%m-%dT%H:%M'],
|
||
widget=forms.DateTimeInput(format='%Y-%m-%dT%H:%M', attrs={'type': 'datetime-local'}))
|
||
tags_text = forms.CharField(required=False, label='Stressors', max_length=500,
|
||
help_text='Separate tags with commas, for example work, sensory overload.')
|
||
symptoms = forms.MultipleChoiceField(required=False, choices=SYMPTOMS,
|
||
widget=forms.CheckboxSelectMultiple, label='Physical symptoms')
|
||
|
||
class Meta:
|
||
model = StressEntry
|
||
fields = ('recorded_at', 'timing', 'score', 'note', 'symptoms')
|
||
widgets = {
|
||
'score': forms.NumberInput(attrs={'min': 0, 'max': 10, 'inputmode': 'numeric'}),
|
||
'note': forms.Textarea(attrs={'rows': 3, 'placeholder': 'Optional note'}),
|
||
}
|
||
|
||
def __init__(self, *args, **kwargs):
|
||
super().__init__(*args, **kwargs)
|
||
self.fields['score'].label = 'Stress (0–10)'
|
||
self.fields['timing'].label = 'When relative to sleep'
|
||
if self.instance.pk:
|
||
self.fields['recorded_at'].initial = timezone.localtime(self.instance.recorded_at)
|
||
self.fields['tags_text'].initial = ', '.join(self.instance.tags)
|
||
self.fields['symptoms'].initial = self.instance.symptoms
|
||
elif not self.is_bound:
|
||
self.fields['recorded_at'].initial = timezone.localtime(timezone.now())
|
||
|
||
def clean_tags_text(self):
|
||
raw = self.cleaned_data['tags_text']
|
||
return normalize_tags([part.strip() for part in raw.split(',') if part.strip()])
|
||
|
||
def clean_symptoms(self):
|
||
return normalize_symptoms(self.cleaned_data['symptoms'])
|
||
|
||
def save(self, commit=True):
|
||
previous_score = None
|
||
if self.instance.pk and self.instance.daily_date is not None:
|
||
previous_score = StressEntry.objects.only('score').get(pk=self.instance.pk).score
|
||
entry = super().save(commit=False)
|
||
if entry.daily_date is not None:
|
||
entry.record_score(self.cleaned_data['score'], previous_score=previous_score)
|
||
entry.tags = self.cleaned_data['tags_text']
|
||
entry.symptoms = self.cleaned_data['symptoms']
|
||
if commit:
|
||
entry.save()
|
||
return entry
|