Search code examples
djangodjango-formsdjango-allauth

How can I override allauth's SignupForm class so that I can remove the emailfield's label?


Screenshot of the rendered form

I have done all necessary imports and the code is fine but the emailfield's label still shows up even after setting it to false.

class SignupForm(forms.Form):
    def __init__(self, *args, **kwargs):
        super(SignupForm, self).__init__(*args, **kwargs)
        self.fields['username'].label = False
        self.fields['password1'].label = False
        self.fields['password2'].label = False
        self.fields['email'].label = False

    def signup(self, request, user):
        user.username = self.cleaned_data['username']
        user.email = self.cleaned_data['email']
        user.password = self.cleaned_data['password']
        user.save(commit=False)

This is the allauth/accounts/forms.py

class BaseSignupForm(_base_signup_form_class()):
    username = forms.CharField(label=_("Username"),
                           min_length=app_settings.USERNAME_MIN_LENGTH,
                           widget=forms.TextInput(
                               attrs={'placeholder':
                                      _('Username'),
                                      'autofocus': 'autofocus'}))
    email = forms.EmailField(widget=forms.TextInput(
        attrs={'type': 'email',
           'placeholder': _('E-mail address')}))

    def __init__(self, *args, **kwargs):
        email_required = kwargs.pop('email_required',
                                app_settings.EMAIL_REQUIRED)
        self.username_required = kwargs.pop('username_required',
                                        app_settings.USERNAME_REQUIRED)
        super(BaseSignupForm, self).__init__(*args, **kwargs)
        username_field = self.fields['username']
        username_field.max_length = get_username_max_length()
        username_field.validators.append(
            validators.MaxLengthValidator(username_field.max_length))

        # field order may contain additional fields from our base class,
        # so take proper care when reordering...
        field_order = ['email', 'username']
        merged_field_order = list(self.fields.keys())
        if email_required:
            self.fields["email"].label = ugettext("E-mail")
            self.fields["email"].required = True
        else:
            self.fields["email"].label = ugettext("E-mail (optional)")
            self.fields["email"].required = False
            self.fields["email"].widget.is_required = False
            if self.username_required:
                field_order = ['username', 'email']...

I believe the "if email_required" to be the problem. Any help to show what I'm doing wrong will be appreciated. Thanks


Solution

  • I finally got it to render as I wanted. I used:

    self.helper = FormHelper()
        self.helper.form_show_labels = False
    

    and a {% crispy form %} tag.