From 76d492a5b18aa2b6e879e797b5fd37236c6cf920 Mon Sep 17 00:00:00 2001 From: Gabriel Augendre Date: Tue, 1 Nov 2022 11:20:44 +0100 Subject: [PATCH] Separate character and other paths --- src/character/forms.py | 30 +++++++++++++++++-- .../character/paths_and_capabilities.html | 7 +++-- src/character/views.py | 4 ++- 3 files changed, 35 insertions(+), 6 deletions(-) diff --git a/src/character/forms.py b/src/character/forms.py index 2bc8c42..8d25a0e 100644 --- a/src/character/forms.py +++ b/src/character/forms.py @@ -1,4 +1,6 @@ from django import forms +from django.core.exceptions import ValidationError +from django.db.models import Q from character.models import Character, Path @@ -10,12 +12,34 @@ class EquipmentForm(forms.ModelForm): class AddPathForm(forms.Form): - path = forms.ModelChoiceField(Path.objects.none()) + character_path = forms.ModelChoiceField( + Path.objects.none(), + required=False, + empty_label="----- Voies liées au personnage -----", + ) + other_path = forms.ModelChoiceField( + Path.objects.none(), required=False, empty_label="----- Autres voies -----" + ) def __init__(self, character: Character, *args, **kwargs): super().__init__(*args, **kwargs) paths = {cap.path_id for cap in character.capabilities.all()} - self.fields["path"].queryset = Path.objects.exclude(pk__in=paths).order_by( + paths = Path.objects.exclude(pk__in=paths).order_by( "profile__name", "race__name" ) - self.fields["path"].widget.attrs["class"] = "form-select" + character_paths = paths.filter( + Q(profile=character.profile) | Q(race=character.race) + ) + self.fields["character_path"].queryset = character_paths + self.fields["character_path"].widget.attrs["class"] = "form-select" + self.fields["other_path"].queryset = paths.exclude( + pk__in={path.pk for path in character_paths} + ) + self.fields["other_path"].widget.attrs["class"] = "form-select" + + def clean(self): + cleaned_data = super().clean() + values = [cleaned_data.get("character_path"), cleaned_data.get("other_path")] + if len(list(filter(None, values))) != 1: + raise ValidationError("Vous devez sélectionner une seule valeur.") + return cleaned_data diff --git a/src/character/templates/character/paths_and_capabilities.html b/src/character/templates/character/paths_and_capabilities.html index e997d8b..795c8a1 100644 --- a/src/character/templates/character/paths_and_capabilities.html +++ b/src/character/templates/character/paths_and_capabilities.html @@ -1,10 +1,13 @@ +{% load django_bootstrap5 %}
{% csrf_token %}
-
+
+ {% bootstrap_form_errors add_path_form %}
- {{ add_path_form.path }} + {{ add_path_form.character_path }} + {{ add_path_form.other_path }}