From 625825cf3f13f6c263ca0e37ad5dae5b8fbae409 Mon Sep 17 00:00:00 2001 From: Ludovic Stephan Date: Fri, 7 Dec 2018 17:04:18 +0100 Subject: [PATCH] =?UTF-8?q?Am=C3=A9liore=20`TemplateLabelField`?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Rajouter une option pour `option_template_name` et `context_object_name` dans la classe, et documente mieux. Répercute ces changements dans `InscriptionReventeForm`. --- bda/forms.py | 27 ++++++++++++------- ...heckbox_table.html => checkbox_table.html} | 0 2 files changed, 18 insertions(+), 9 deletions(-) rename bda/templates/bda/forms/{spectacle_checkbox_table.html => checkbox_table.html} (100%) diff --git a/bda/forms.py b/bda/forms.py index 8e3038a6..8230056d 100644 --- a/bda/forms.py +++ b/bda/forms.py @@ -113,20 +113,31 @@ class AnnulForm(forms.Form): class TemplateLabelField(forms.ModelMultipleChoiceField): """ - Offers an option to render a label with Django template rendering + Extends ModelMultipleChoiceField to offer two more customization options : + - `label_from_instance` can be used with a template file + - the widget rendering template can be specified with `option_template_name` """ - def __init__(self, template_name=None, context_object_name="obj", *args, **kwargs): + def __init__( + self, + label_template_name=None, + context_object_name="obj", + option_template_name=None, + *args, + **kwargs + ): super().__init__(*args, **kwargs) - self.template_name = template_name + self.label_template_name = label_template_name self.context_object_name = context_object_name + if option_template_name is not None: + self.widget.option_template_name = option_template_name def label_from_instance(self, obj): - if self.template_name is None: + if self.label_template_name is None: return super().label_from_instance(obj) else: return loader.render_to_string( - self.template_name, context={self.context_object_name: obj} + self.label_template_name, context={self.context_object_name: obj} ) @@ -135,7 +146,8 @@ class InscriptionReventeForm(forms.Form): queryset=Spectacle.objects.none(), widget=forms.CheckboxSelectMultiple, required=False, - template_name="bda/forms/spectacle_label_table.html", + label_template_name="bda/forms/spectacle_label_table.html", + option_template_name="bda/forms/checkbox_table.html", context_object_name="spectacle", ) @@ -144,9 +156,6 @@ class InscriptionReventeForm(forms.Form): self.fields["spectacles"].queryset = tirage.spectacle_set.select_related( "location" ).filter(date__gte=timezone.now()) - self.fields[ - "spectacles" - ].widget.option_template_name = "bda/forms/spectacle_checkbox_table.html" class ReventeTirageAnnulForm(forms.Form): diff --git a/bda/templates/bda/forms/spectacle_checkbox_table.html b/bda/templates/bda/forms/checkbox_table.html similarity index 100% rename from bda/templates/bda/forms/spectacle_checkbox_table.html rename to bda/templates/bda/forms/checkbox_table.html