Améliore TemplateLabelField

- Rajouter une option pour `option_template_name` et `context_object_name` dans la classe, et documente mieux. Répercute ces changements dans `InscriptionReventeForm`.
This commit is contained in:
Ludovic Stephan 2018-12-07 17:04:18 +01:00
parent dbd017f680
commit 625825cf3f
2 changed files with 18 additions and 9 deletions

View file

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