Skip to content

Instantly share code, notes, and snippets.

@agusmakmun
Last active November 23, 2016 15:44
Show Gist options
  • Save agusmakmun/86775bfff6d20061e78b2d12b0b00885 to your computer and use it in GitHub Desktop.
Save agusmakmun/86775bfff6d20061e78b2d12b0b00885 to your computer and use it in GitHub Desktop.
from django import forms
from django.contrib.auth.models import User
from yourapp.models import Profile
class SignUpForm(forms.ModelForm):
username = forms.CharField(
required=True,
widget=forms.TextInput()
)
email = forms.EmailField(
required=True,
widget=forms.EmailInput()
)
password = forms.CharField(
widget=forms.PasswordInput()
)
password2 = forms.CharField(
label=_("Password Confirmation"),
widget=forms.PasswordInput()
)
error_message = {
'password_mismatch': _("The two password didn't match."),
}
class Meta:
model = Profile
fields = '__all__'
exclude = ['user',]
def clean_password2(self):
password1 = self.cleaned_data.get('password')
password2 = self.cleaned_data.get('password2')
if password1 and password2 and password1 != password2:
raise forms.ValidationError(
self.error_message['password_mismatch'],
code='password_mismatch',
)
return password2
def save(self, commit=True):
user = super(SignUpForm, self).save(commit=False)
user_registration = User.objects.create_user(
username=self.cleaned_data['username'],
password=self.cleaned_data['password'],
email=self.cleaned_data['email']
)
if commit:
user_registration.save()
return user_registration
from django.db import models
from django.contrib.auth.models import User
class Profile(models.Model):
user = models.ForeignKey(
User, related_name='user_profile'
)
avatar = models.ImageField(
upload_to='uploads/avatar/%Y/%m/%d',
null=True, blank=True
)
about = models.TextField(
null=True, blank=True
)
def __str__(self):
return self.user.username
{% extends "base.html" %}
{% block content %}
<form action="." method="POST" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Register Now</button>
</form>
{% endblock %}
from django.shortcuts import (render, redirect)
from django.contrib.auth import (authenticate, login, logout)
from yourapp.models import Profile
from yourapp.forms import SignUpForm
def register(request):
if request.method == 'POST':
form = SignUpForm(request.POST, request.FILES, instance=Profile())
if form.is_valid():
cd = form.cleaned_data
username = cd['username']
password = cd['password']
user = authenticate(username=username, password=password)
initial = form.save(commit=False)
initial.user = user
initial.save()
form.save()
if user is not None and user.is_active:
login(request, user)
return redirect('/')
else:
form = SignUpForm(instance=Profile())
return render(request, 'yourapp/register.html', {'form':form})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment