from django import forms from django.urls import reverse from games.models import Device, Edition, Game, Platform, Purchase, Session custom_date_widget = forms.DateInput(attrs={"type": "date"}) custom_datetime_widget = forms.DateTimeInput( attrs={"type": "datetime-local"}, format="%Y-%m-%d %H:%M" ) autofocus_input_widget = forms.TextInput(attrs={"autofocus": "autofocus"}) class SessionForm(forms.ModelForm): # purchase = forms.ModelChoiceField( # queryset=Purchase.objects.filter(date_refunded=None).order_by("edition__name") # ) purchase = forms.ModelChoiceField( queryset=Purchase.objects.order_by("edition__sort_name"), widget=forms.Select(attrs={"autofocus": "autofocus"}), ) device = forms.ModelChoiceField(queryset=Device.objects.order_by("name")) class Meta: widgets = { "timestamp_start": custom_datetime_widget, "timestamp_end": custom_datetime_widget, } model = Session fields = [ "purchase", "timestamp_start", "timestamp_end", "duration_manual", "device", "note", ] class EditionChoiceField(forms.ModelChoiceField): def label_from_instance(self, obj) -> str: return f"{obj.sort_name} ({obj.platform}, {obj.year_released})" class IncludePlatformSelect(forms.Select): def create_option(self, name, value, *args, **kwargs): option = super().create_option(name, value, *args, **kwargs) if value: option["attrs"]["data-platform"] = value.instance.platform.id return option class PurchaseForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # Automatically update related_purchase