Skip to content

Instantly share code, notes, and snippets.

@t-book
Last active November 13, 2019 10:41
Show Gist options
  • Save t-book/197f4f2289304b6c1481920fb61e2904 to your computer and use it in GitHub Desktop.
Save t-book/197f4f2289304b6c1481920fb61e2904 to your computer and use it in GitHub Desktop.

Add custom fields to Registration form

We assume the use of geonode-project. For adding new fields to geonodes registration form we create a custom Signup form as part of our geonode project. In this example we're adding first_name and last_name to the registration form. To do so we're creating a forms.py in our project folder

forms.py

from django import forms
from django.contrib.auth.forms import UserCreationForm
from geonode.people.models import Profile


class CustomSignupForm(UserCreationForm):
    first_name = forms.CharField(max_length=30, required=True)
    last_name = forms.CharField(max_length=30, required=True)
    email = forms.EmailField(max_length=254)
    field_order = ['first_name', 'last_name', 'email', 'username']

    class Meta:
        model = Profile
        fields = ('email', 'username', 'last_name')

    def save(self, commit=True):
        user = super(UserCreationForm, self).save(commit=False)
        user.set_password(self.cleaned_data["password1"])
        user.first_name = self.cleaned_data['first_name']
        user.last_name = self.cleaned_data['last_name']

    def clean_username(self):
        # Since User.username is unique, this check is redundant,
        # but it sets a nicer error message than the ORM. See #13147.
        username = self.cleaned_data["username"]
        try:
            Profile.objects.get(username=username)
        except Profile.DoesNotExist:
            return username
        raise forms.ValidationError(
            self.error_messages['duplicate_username'],
            code='duplicate_username',
        )
        
        if commit:
            user.save()
        return user

All what is left to do is to tell Django to use our new form.

Update your settings with:

local_settings.py

ACCOUNT_SIGNUP_FORM_CLASS = os.getenv("ACCOUNT_SIGNUP_FORM_CLASS",
                                          'my_geonode.forms.CustomSignupForm')

How to continue

In case you need more advanced customisations make yourself familiar with custom user models (geonode uses app profile which subclasses AbstractUser). Furter visit docs of django-allauth.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment