Files
Django_TasksApp/main/planner/forms.py
T
2026-09-30 17:25:25 +02:00

237 lines
9.0 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth import get_user_model
from django.urls import reverse
from django.utils import timezone
from zoneinfo import available_timezones
from .models import FastingSettings, NeckHeadacheCheckIn, SickDaySettings, SleepCheckIn, Task, UserSettings, Workout
from .timezones import localdate_for_user
class TaskForm(forms.ModelForm):
class Meta:
model = Task
fields = (
'title', 'description', 'estimated_duration_minutes', 'priority', 'category',
'scheduled_for', 'is_recurring', 'recurrence_interval', 'recurrence_unit',
'defer_days', 'is_active', 'is_outdoor', 'weather_profile', 'required_on_sick_day', 'parent_task',
)
widgets = {
'description': forms.Textarea(attrs={'rows': 5}),
'scheduled_for': forms.DateInput(attrs={'type': 'date'}),
}
def __init__(self, *args, owner=None, **kwargs):
super().__init__(*args, **kwargs)
self.owner = owner
parents = Task.objects.filter(parent_task__isnull=True)
if owner is not None:
parents = parents.filter(owner=owner)
if self.instance.pk:
# Keeping choices top-level prevents accidental deep nesting in the UI.
parents = parents.exclude(pk=self.instance.pk)
self.fields['parent_task'].queryset = parents
self.fields['defer_days'].help_text = 'Days to defer this one-time task after it is missed.'
category_id = self['category'].id_for_label
self.fields['category'].widget.attrs.update({
'autocomplete': 'off',
'role': 'combobox',
'aria-autocomplete': 'list',
'aria-expanded': 'false',
'aria-controls': f'{category_id}-suggestions',
'aria-haspopup': 'listbox',
'data-category-input': '',
'data-suggestions-url': reverse('planner:category-suggestions'),
})
def clean_category(self):
category = self.cleaned_data['category'].strip()
if not category or self.owner is None:
return category
for existing_category in Task.objects.filter(owner=self.owner).exclude(category='').order_by('pk').values_list('category', flat=True):
normalized = existing_category.strip()
if normalized.casefold() == category.casefold():
return normalized
return category
class DailyPlannerForm(forms.Form):
selected_date = forms.DateField(
label='Plan for',
widget=forms.DateInput(attrs={'type': 'date'}),
)
energy_level = forms.TypedChoiceField(
label='Energy level',
coerce=int,
choices=(
(1, '1 — Very low (15 min)'),
(2, '2 — Low (30 min)'),
(3, '3 — Steady (60 min)'),
(4, '4 — High (90 min)'),
(5, '5 — Fully charged (180 min)'),
),
)
DAILY_FASTING_DURATION_CHOICES = (
('Beginner', (
(12 * 60, '12:12 — Fast 12 hours, eat within 12 hours'),
(13 * 60, '13:11 — Fast 13 hours, eat within 11 hours'),
(14 * 60, '14:10 — Fast 14 hours, eat within 10 hours'),
(15 * 60, '15:9 — Fast 15 hours, eat within 9 hours'),
)),
('Experienced', (
(16 * 60, '16:8 — Fast 16 hours, eat within 8 hours'),
(17 * 60, '17:7 — Fast 17 hours, eat within 7 hours'),
(18 * 60, '18:6 — Fast 18 hours, eat within 6 hours'),
)),
('Professional', (
(19 * 60, '19:5 — Fast 19 hours, eat within 5 hours'),
(20 * 60, '20:4 — Fast 20 hours, eat within 4 hours'),
(21 * 60, '21:3 — Fast 21 hours, eat within 3 hours'),
(22 * 60, '22:2 — Fast 22 hours, eat within 2 hours'),
)),
)
class FastingSettingsForm(forms.ModelForm):
fasting_duration_minutes = forms.TypedChoiceField(
label='Daily fasting schedule',
choices=DAILY_FASTING_DURATION_CHOICES,
coerce=int,
help_text='Choose a daily fasting and eating-window rhythm.',
)
class Meta:
model = FastingSettings
fields = ('enabled', 'fasting_start_time', 'fasting_duration_minutes')
widgets = {
'fasting_start_time': forms.TimeInput(attrs={'type': 'time'}),
}
labels = {
'fasting_start_time': 'Fasting starts at',
}
help_texts = {
}
TIME_ZONE_CHOICES = tuple((name, name) for name in sorted(available_timezones()))
class TimeZoneSettingsForm(forms.ModelForm):
time_zone = forms.ChoiceField(label='Time zone', choices=TIME_ZONE_CHOICES)
class Meta:
model = UserSettings
fields = ('time_zone',)
help_texts = {
'time_zone': 'Used for dates and displayed times, including fasting.',
}
class UserSettingsForm(forms.ModelForm):
class Meta:
model = UserSettings
fields = ('latitude', 'longitude')
widgets = {
'latitude': forms.TextInput(attrs={'inputmode': 'decimal', 'autocomplete': 'off', 'placeholder': 'e.g. 52.36760'}),
'longitude': forms.TextInput(attrs={'inputmode': 'decimal', 'autocomplete': 'off', 'placeholder': 'e.g. 4.90410'}),
}
help_texts = {
'latitude': 'Between -90 and 90.',
'longitude': 'Between -180 and 180.',
}
class SickDaySettingsForm(forms.ModelForm):
class Meta:
model = SickDaySettings
fields = ('enabled', 'recovery_date')
widgets = {'recovery_date': forms.DateInput(attrs={'type': 'date'})}
help_texts = {'recovery_date': 'Optional. Tasks resume the day after this date.'}
class RegistrationForm(UserCreationForm):
class Meta(UserCreationForm.Meta):
model = get_user_model()
fields = ('username',)
class WorkoutForm(forms.ModelForm):
class Meta:
model = Workout
fields = ('name', 'scheduled_for', 'is_daily_recurring', 'duration_minutes', 'calories_burned')
widgets = {'scheduled_for': forms.DateInput(attrs={'type': 'date'})}
help_texts = {
'is_daily_recurring': 'Show this workout every day from its start date.',
'calories_burned': 'Optional; only completed workouts with a value contribute to today’s total.',
}
class SleepCheckInForm(forms.ModelForm):
class Meta:
model = SleepCheckIn
fields = ('wake_up_date', 'rested_score', 'watch_sleep_score', 'note')
widgets = {
'wake_up_date': forms.DateInput(attrs={'type': 'date'}),
'rested_score': forms.NumberInput(attrs={'min': 0, 'max': 10, 'inputmode': 'numeric'}),
'watch_sleep_score': forms.NumberInput(attrs={'min': 0, 'max': 100, 'inputmode': 'numeric'}),
'note': forms.TextInput(attrs={'maxlength': 500, 'placeholder': 'Anything useful to remember?'}),
}
labels = {
'wake_up_date': 'Wake-up date',
'rested_score': 'How rested (0–10)',
'watch_sleep_score': 'Watch sleep score (0–100%, optional)',
'note': 'Note (optional)',
}
def __init__(self, *args, user=None, **kwargs):
super().__init__(*args, **kwargs)
self.user = user
def clean_wake_up_date(self):
wake_up_date = self.cleaned_data['wake_up_date']
today = localdate_for_user(self.user) if self.user else timezone.localdate()
if wake_up_date > today:
raise forms.ValidationError('Sleep can only be recorded for today or earlier.')
return wake_up_date
class NeckHeadacheCheckInForm(forms.ModelForm):
class Meta:
model = NeckHeadacheCheckIn
fields = (
'check_in_date', 'neck_pain_severity', 'headache_severity', 'note',
'had_physiotherapy',
)
widgets = {
'check_in_date': forms.DateInput(attrs={'type': 'date'}),
'neck_pain_severity': forms.NumberInput(attrs={'min': 0, 'max': 10, 'inputmode': 'numeric'}),
'headache_severity': forms.NumberInput(attrs={'min': 0, 'max': 10, 'inputmode': 'numeric'}),
'note': forms.TextInput(attrs={'maxlength': 500, 'placeholder': 'Anything useful to remember?'}),
}
labels = {
'check_in_date': 'Date',
'neck_pain_severity': 'Neck pain (0–10)',
'headache_severity': 'Headache (0–10)',
'note': 'Note (optional)',
'had_physiotherapy': 'I had a physiotherapy session',
}
help_texts = {
'neck_pain_severity': '0 means no pain.',
'headache_severity': '0 means no headache.',
}
def __init__(self, *args, user=None, **kwargs):
super().__init__(*args, **kwargs)
self.user = user
def clean_check_in_date(self):
check_in_date = self.cleaned_data['check_in_date']
today = localdate_for_user(self.user) if self.user else timezone.localdate()
if check_in_date > today:
raise forms.ValidationError('Check-ins can only be recorded for today or earlier.')
return check_in_date