[Answer]-Way to not duplicate codes between "models.py" and "forms.py"?


A ModelForm can have fields that are model-bound and unbound. You can also override the label attribute for a model field without having to re-define the field in your form:

class RegistrationForm(forms.ModelForm):
    class Meta:
        model = MyUser

    error_css_class = 'error'
    required_css_class = 'required' 

    def __init__(self, *args, **kwargs):
        super(RegistrationForm, self).__init__(*args, **kwargs)
        self.fields['full_name'].label = _("Full Name")

    password2 = forms.CharField(
        label=_("Password (again)"),

Although, I don’t see where you’re providing labels for any of your model fields differently in your form. You can always add the label attribute at the model level too:

class MyUser(AbstractBaseUser):
    email = models.EmailField(u'Email Address', max_length=255, unique=True,
    full_name = forms.CharField(u'Full Name', max_length=64)

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['full_name']

Leave a comment