Separate character and other paths

This commit is contained in:
Gabriel Augendre 2022-11-01 11:20:44 +01:00
parent b4d5ca039f
commit 76d492a5b1
3 changed files with 35 additions and 6 deletions

View file

@ -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

View file

@ -1,10 +1,13 @@
{% load django_bootstrap5 %}
<div id="paths-and-capabilities">
<form>
{% csrf_token %}
<div class="row">
<div class="col col-lg-6">
<div class="col">
{% bootstrap_form_errors add_path_form %}
<div class="input-group">
{{ add_path_form.path }}
{{ add_path_form.character_path }}
{{ add_path_form.other_path }}
<button class="btn btn-primary"
hx-target="#paths-and-capabilities"
hx-swap="outerHTML"

View file

@ -41,7 +41,9 @@ def add_path(request, pk: int):
form = AddPathForm(character, request.POST)
context = {"character": character}
if form.is_valid():
path: Path = form.cleaned_data.get("path")
path: Path = form.cleaned_data.get("character_path") or form.cleaned_data.get(
"other_path"
)
cap = path.get_next_capability(character)
character.capabilities.add(cap)
context["add_path_form"] = AddPathForm(character)