register users

Date: March 23rd 2016
Last updated: March 23rd 2016

Cookies, Sessions and User Registration are key parts to a web framework. In this example I look at registering users for a website. Then I will look at login and logout functionality etc.
A user clicks on a link and activates the following url or registration is on the landing page of the website. The url invokes the register_user method in

from django.conf.urls import url
from . import views

app_name = 'surferprofile'
urlpatterns = [
    url(r'^register/$', views.register_user, name='register'),
The post method is in register.html (see next code chunk). If the credentials are correct, the user gets redirected to a generic url. In this case a single forward slash represents my index page.

# make sure to import MyRegistrationForm
from django.http import HttpResponseRedirect
from django.shortcuts import render
from .forms import MyRegistrationForm
from django.contrib import auth
from django.core.context_processors import csrf

def register_user(request):
    if request.method == 'POST':
        form = MyRegistrationForm(request.POST)     # create form object
        if form.is_valid():
            return HttpResponseRedirect('/') # redirect to index page 
    args = {}
    args['form'] = MyRegistrationForm()

    # call to the register.html template to enter registration info
    return render(request, 'surferprofile/register.html', args)

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

class MyRegistrationForm(UserCreationForm):
    email = forms.EmailField(required = True) # You only need an email
    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) = 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:
        return user



<form role="form" action="" method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit">Submit</button>
</form> admin

results matching ""

    No results matching ""