Skip to content

Instantly share code, notes, and snippets.

@heygema
Last active March 25, 2017 04:50
Show Gist options
  • Save heygema/e495b8c2c48ee40e8a291509b5c46c75 to your computer and use it in GitHub Desktop.
Save heygema/e495b8c2c48ee40e8a291509b5c46c75 to your computer and use it in GitHub Desktop.
The example of one file of custom account in django to rule them all !
from django.contrib.auth.models import BaseUserManager
class MyUserManager(BaseUserManager):
def create_user(self, email, password=None, **kwargs):
if email is None:
raise TypeError('user must have an email')
user = self.model(email=self.normalize_email(email))
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, password):
user = self.create_user(email, password=password)
user.is_superuser = True
user.is_admin = True
user.save(using=self.db)
return user
from django.conf import settings
from datetime import datetime, timedelta
from django.core.mail import send_mail
from django.db import models
from django.contrib.auth.models import (
AbstractBaseUser,
PermissionsMixin
)
# User Model
class User(AbstractBaseUser, PermissionsMixin, TimestampedModel):
email = models.EmailField(
verbose_name='email address',
max_length=255,
unique=True)
# this is important
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
# categorize roles
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
objects = MyUserManager()
def __str__(self):
return self.email
def __unicode__(self):
return self.email
def get_full_name(self):
return "{} {}".format(self.first_name, self.last_name)
def get_short_name(self):
return self.first_name
@property
def is_staff(self):
return self.is_admin
def email_user(self, subject, message, from_email=None, **kwargs):
"""To send confirmation email, subscription letter, etc"""
send_mail(subject, message, from_email, [self.email], **kwargs)
# User forms
from django import forms
from django.contrib.auth import (
login,
logout,
authenticate,
get_user_model,
)
from .models import User
from django.contrib import admin
from django.contrib.auth.models import Group
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.contrib.auth.forms import ReadOnlyPasswordHashField
class LoginForm(forms.Form):
email = forms.CharField(label="Email", widget=forms.TextInput(attrs={
'placeholder':'Your Email'
}))
password = forms.CharField(required=True, widget=forms.PasswordInput(attrs={
'placeholder':'Input Password'
}))
def clean(self, *args, **kwargs):
email = self.cleaned_data.get("email")
password = self.cleaned_data.get("password")
if email and password:
user = authenticate(email=email, password=password)
if not user:
raise forms.ValidationError("This user does not exist")
# if user.password != password:
# raise forms.ValidationError('wrong password')
# if not user.check_password(password):
# raise forms.ValidationError("Incorrect password")
if not user.is_active:
raise forms.ValidationError("User is not active")
return super(LoginForm, self).clean(*args , **kwargs)
class RegisterForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(RegisterForm, self).__init__(*args, **kwargs)
self.fields['email'].label = "Email"
self.fields['first_name'].label = "First Name"
self.fields['last_name'].label = "Last Name"
password = forms.CharField(
label="Password",
widget=forms.PasswordInput
)
password_confrim = forms.CharField(
label="Password Confirmation",
widget=forms.PasswordInput
)
class Meta:
model = User
fields = [
'email',
'first_name',
'last_name',
]
def clean_pass(self, *args, **kwargs):
password = self.cleaned_data.get("password")
password_confirm = self.cleaned_data.get("password_confirm")
if password and password_confirm and password != password_confirm:
raise forms.ValidationError('Password didn\'t match')
return password_confirm
def save(self, commit=True):
"""Save user and hash the password"""
user = super(RegisterForm, self).save(commit=False)
user.set_password(self.cleaned_data.get("password"))
if commit:
user.save()
return user
class UserChangeForm(forms.ModelForm):
"""for updating user data, etc"""
password = ReadOnlyPasswordHashField()
class Meta:
model = User
fields = [
'email',
'password',
'is_active',
'is_admin'
]
def clean_pass(self, *args, **kwargs):
return self.initial["password"]
# Lastly this class intended for register it in admin site
class UserAdmin(BaseUserAdmin):
# The forms to add and change user instances
form = UserChangeForm
add_form = RegisterForm
# The fields to be used in displaying the User model.
# These override the definitions on the base UserAdmin
# that reference specific fields on auth.User.
list_display = ('email', 'first_name', 'last_name', 'is_admin')
list_filter = ('is_admin',)
fieldsets = (
(None, {'fields': ('email', 'password')}),
('Personal info', {'fields': ('first_name', 'last_name',)}),
('Permissions', {'fields': ('is_admin',)}),
)
# add_fieldsets is not a standard ModelAdmin attribute. UserAdmin
# overrides get_fieldsets to use this attribute when creating a user.
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('email', 'password', 'password_confirm')}
),
)
search_fields = ('email',)
ordering = ('email',)
filter_horizontal = ()
# Now register the new UserAdmin...
admin.site.register(User, UserAdmin)
# ... and, since we're not using Django's built-in permissions,
# unregister the Group model from admin.
admin.site.unregister(Group)
from django.shortcuts import render, get_object_or_404, redirect
from django.core.urlresolvers import reverse
from django.contrib.auth import (
login,
logout,
authenticate,
get_user_model,
)
from django.contrib.auth.forms import PasswordResetForm
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse
from .forms import LoginForm, RegisterForm
# from .models import User
def register_view(request):
form = RegisterForm(request.POST or None)
return render(request,"account/register.html", {
"form":form
})
def login_view(request):
title = "login"
form = LoginForm(request.POST or None)
if form.is_valid():
email = form.cleaned_data.get("email")
password = form.cleaned_data.get("password")
user = authenticate(email=email, password=password)
login(request, user)
return redirect("logged")
return render(request, "account/login.html",{
"form": form,
"title": title
})
@login_required
def logged(request):
return HttpResponse("Logged In !")
def logout_view(request):
logout(request)
return redirect("home")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment