Skip to content

Instantly share code, notes, and snippets.

Last active January 27, 2023 08:31
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
how to change one attribute of a Django form field
from django import forms
class MyGenericForm(forms.Form):
valid_from = forms.DateField(
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"),
# solution to be improved
class SpecificForm0(MyGenericForm):
valid_from = _same_as(
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