Skip to content

Instantly share code, notes, and snippets.

@ergusto
Created July 30, 2014 12:05
Show Gist options
  • Save ergusto/5a63f52eb7d9a80e2226 to your computer and use it in GitHub Desktop.
Save ergusto/5a63f52eb7d9a80e2226 to your computer and use it in GitHub Desktop.
Registration with CBVs
from django import forms
from django.forms import ModelForm
from django.contrib.auth.models import User
class RegistrationForm(ModelForm):
password_1 = forms.CharField(label=(u'Verify Password'), widget=forms.PasswordInput())
class Meta:
model = User
fields = ('username', 'password')
def __init__(self, *args, **kwargs):
super(RegistrationForm, self).__init__(*args, **kwargs)
self.fields['username'].help_text = None
self.fields['password'].widget = forms.PasswordInput()
def clean_username(self):
username = self.cleaned_data['username']
try:
User.objects.get(username=username)
except User.DoesNotExist:
return username
raise forms.ValidationError("That username is already taken. Please select another.")
def clean(self):
password = self.cleaned_data.get('password', None)
password_1 = self.cleaned_data.get('password_1', None)
if password and password_1 and (password == password_1):
return self.cleaned_data
else:
raise forms.ValidationError("The passwords did not match. Please try again.")
def save(self, commit=True):
user = super(RegistrationForm, self).save(commit=False)
user.set_password(self.cleaned_data['password'])
if commit:
user.save()
return user
from django.shortcuts import render
from django.core.urlresolvers import reverse
from django.http import HttpResponse, HttpResponseRedirect
from django.views.generic import FormView
from django.contrib.auth import authenticate, login
from forms import RegistrationForm
# Create your views here.
class RegisterView(FormView):
form_class = RegistrationForm
template_name = 'registration/register.html'
def get(self, request, *args, **kwargs):
form = self.form_class()
return render(request, self.template_name, {'form': form})
def auth_login(self, request, username, password):
user = authenticate(username=username, password=password)
login(request, user)
def post(self, request, *args, **kwargs):
form = self.form_class(request.POST)
if form.is_valid():
form.save()
self.auth_login(self.request, request.POST['username'], request.POST['password'])
return HttpResponseRedirect(reverse('index'))
else:
return render(request, self.template_name, {'form': form})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment