As we know, the Django authors provide a coding style guide, to use as guidance when writing Django applications. However, the document provided mentions nothing specifically about forms.
Is there already a common pattern in use for this? Is the best to follow the Model style guide, with some minor adaptions? Below is how I define forms at the moment, and looking through a random selection of popular Django apps, I fail to see much consistency that agrees with my method. Can those using Django for many years now provide a recommendation?
class ExampleForm(BetterModelForm):
# start with field definitions, as with Django Model style guide
name = forms.CharField(label="Your Name")
town = forms.CharField(label="Ideal city?")
class Meta:
# all Meta class definitions, as with Django Model style guide
model = models.Example
fields = ['name', 'town', 'example_field']
def save(self):
# ...
def clean_name(self):
# ...
def clean_town(self):
# ...
def clean(self):
# ...
def custom_function(self):
# ...
So, my style is to start with the fields, then the Meta class (with a clear line before the definition), then the save method, then any clean methods, and then any custom methods. Is this close to the standard, recommended way of doing it, if such a thing exists?
Many of django’s model style guide lines derive from python’s pep8 guidelines, so if you haven’t done it yet have a look there! There aren’t any specific guidelines for forms, but it’s a good practice for sure to apply the rules for models to forms as well if possible (eg. order of the inner meta class).
But probably the most important point here is to keep some consistency over your whole project, so that eg. other developers wouldn’t miss a certain method definition in long form class if they are expecting it at a certain point… But I guess everybody will agree that form classes tend to get very complex and there aren’t any official guildelines for them!