Making custom model fields are a great thing to save a lot of time. If you need a lot of custom validation around your modelforms and don’t want to do a lot of copy and pasting then create a custom model field.
For example, I have the need for a user to input a lot of hostnames and domains and got sick of doing custom validation in each model form I created. So I created a model field for it.
So here it is
class HostnameField(models.CharField):
def clean(self, value):
value = super(HostnameField, self).clean(value)
import re
regex = re.compile("^([a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,6}$")
r = regex.search(string)
if len(r.groups()) == 0:
raise models.ValidationError("You need to enter a valid hostname/domain")
return value
The regex might not be the best, but it seems to cover all the use cases I tried on it.