Skip to content

Instantly share code, notes, and snippets.

@greenkey
Last active January 27, 2023 08:31
Show Gist options
  • Save greenkey/dff7aa6a1b07f1edbe0ead5c576d9cf8 to your computer and use it in GitHub Desktop.
Save greenkey/dff7aa6a1b07f1edbe0ead5c576d9cf8 to your computer and use it in GitHub Desktop.
how to change one attribute of a Django form field
from django import forms
class MyGenericForm(forms.Form):
valid_from = forms.DateField(
required=False,
label='Validity Start',
help_text="The first date that this rate is valid.",
widget=forms.DateInput(attrs={"placeholder": "YYYY-MM-DD"}, format="%Y-%m-%d"),
input_formats=["%Y-%m-%d"],
)
# solution to be improved
class SpecificForm0(MyGenericForm):
valid_from = _same_as(
MyGenericForm.declared_fields["valid_from"],
but={"label": "Validity Start Date"},
)
def _same_as(field: forms.Field, but: dict[str, Any]):
field = copy(field)
for attr, val in but.items():
setattr(field, attr, val)
return field
# first solution provided by ChatGPT
class SpecificForm1(MyGenericForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields["valid_from"].label = "Validity Start Date"
# second solution provided by ChatGPT
class SpecificForm2(MyGenericForm):
valid_from = MyGenericForm.declared_fields["valid_from"]
valid_from.label = "Validity Start Date"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment