extending the User model

Date: March 24th 2016
Last updated: March 24th 2016

The User model is built-in to Django. In previous examples I have shown the User model as having a first name, last name and email. However, it is sometimes convenient to capture more information on registration. This can be done by extending the User model. This article helped me: http://stackoverflow.com/questions/27832076/modelform-with-onetoonefield-in-django.

In this example I extend the User model to add custom fields when a new user registers to the website. The reason I am doing this is to create a User and a Profile simultaneously, rather than making the new user complete another form after registration.

Update views.py

def register_user(request):
    if request.method == 'POST':
        user_form = MyRegistrationForm(request.POST)
        profile_form = CreateSurferForm(request.POST)

        #if form.is_valid(): #<==== replaced with the following solution

        ######################## solution #############################
        # also note where profile_form comes from above
        # form.is_valid has been replaced with user_form.is_valid
        if all((user_form.is_valid(), profile_form.is_valid())):
            userid = user_form.save()
            profile = profile_form.save(commit=False)
            profile.user = userid
            profile.save()
        ###############################################################

            # authenticate the new user
            new_user = authenticate(username=user_form.cleaned_data['username'],
                                    password=user_form.cleaned_data['password1'],)
            login(request, new_user)
            return redirect('/userhome/{}/'.format(new_user.id))
            # use redirect to go to the users new home page

    args = {}
    args.update(csrf(request))
    args['form'] = MyRegistrationForm()
    args['profileform'] = CreateSurferForm()
    return render(request, 'surferprofile/register.html', args)

Add CreateSurferForm to Forms.py (both forms shown)

from django import forms
from surferprofile.models import Surfer
from django.contrib.auth.models import User 
from django.contrib.auth.forms import UserCreationForm

class MyRegistrationForm(UserCreationForm):
    email = forms.EmailField(required = True)
    first_name = forms.CharField(required = False)
    last_name = forms.CharField(required = False)
    birthday = forms.DateField(required = False)

    class Meta:
        model = User
        fields = ('username', 'email', 'password1', 'password2')

    def save(self,commit = True):
        user = super(MyRegistrationForm, self).save(commit = False)
        user.email = self.cleaned_data['email']
        user.first_name = self.cleaned_data['first_name']
        user.last_name = self.cleaned_data['last_name']
        user.birthday = self.cleaned_data['birthday']
        if commit:
            user.save()
        return user


class CreateSurferForm(forms.ModelForm):
    class Meta:
        model = Surfer
        fields = ['height', 'weight', 'hometown','stance']

Update register.html

<body>
    <h1>Register</h1>

    <form role="form" action="" method="post">

        {% csrf_token %}

        {{ form.as_p }} <!-- user_form assigned to args (see views.py) -->
        {{ profileform.as_p }} <!-- profile_form assigned to args (see views.py) -->

        <button type="submit">Submit</button>
    </form>

</body>

results matching ""

    No results matching ""