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.
urls.py
A user clicks on a link and activates the following url or registration is on the landing page of the website. The url http://127.0.0.1:8080/register/ invokes the register_user method in views.py.
from django.conf.urls import url
from . import views
app_name = 'surferprofile'
urlpatterns = [
url(r'^register/$', views.register_user, name='register'),
]
views.py
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():
form.save()
return HttpResponseRedirect('/') # redirect to index page
args = {}
args.update(csrf(request))
args['form'] = MyRegistrationForm()
# call to the register.html template to enter registration info
return render(request, 'surferprofile/register.html', args)
forms.py
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)
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
register.html
<h1>Register</h1>
<form role="form" action="" method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Submit</button>
</form>