Last active
July 18, 2020 05:53
-
-
Save sesh/4490a25bf5aafa5c1b7e3cf8a30f1b64 to your computer and use it in GitHub Desktop.
Django Custom User Model
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.contrib import admin | |
from django.contrib.auth.admin import UserAdmin | |
from django.utils.translation import ugettext_lazy as _ | |
from .models import User | |
class CustomUserAdmin(UserAdmin): | |
fieldsets = ( | |
(None, {'fields': ('email', 'password')}), | |
(_('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser', | |
'groups', 'user_permissions')}), | |
(_('Important dates'), {'fields': ('last_login', 'date_joined')}), | |
) | |
list_display = ('email', 'name', 'is_staff') | |
search_fields = ('name', 'email') | |
ordering = ['email'] | |
admin.site.register(User, CustomUserAdmin) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django import forms | |
from .models import User | |
class SignUpForm(forms.Form): | |
email = forms.EmailField() | |
password = forms.CharField(widget=forms.PasswordInput()) | |
password_again = forms.CharField(widget=forms.PasswordInput()) | |
def clean_email(self): | |
value = self.cleaned_data['email'].strip() | |
if User.objects.filter(email=value): | |
raise forms.ValidationError("That email is already taken") | |
return value | |
def clean(self): | |
cleaned_data = super().clean() | |
if cleaned_data['password'] != cleaned_data['password_again']: | |
raise forms.ValidationError("The passwords you entered did not match") |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.db import models | |
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, UserManager | |
from django.utils import timezone | |
class CustomUserManager(UserManager): | |
def _create_user(self, email, password, **extra_fields): | |
""" | |
Creates and saves a User with the given username, email and password. | |
""" | |
if not email: | |
raise ValueError('The given email address must be set') | |
email = self.normalize_email(email) | |
user = self.model(email=email, **extra_fields) | |
user.set_password(password) | |
user.save(using=self._db) | |
return user | |
def create_user(self, email=None, password=None, **extra_fields): | |
extra_fields.setdefault('is_staff', False) | |
extra_fields.setdefault('is_superuser', False) | |
return self._create_user(email, password, **extra_fields) | |
def create_superuser(self, email, password, **extra_fields): | |
extra_fields.setdefault('is_staff', True) | |
extra_fields.setdefault('is_superuser', True) | |
if extra_fields.get('is_staff') is not True: | |
raise ValueError('Superuser must have is_staff=True.') | |
if extra_fields.get('is_superuser') is not True: | |
raise ValueError('Superuser must have is_superuser=True.') | |
return self._create_user(email, password, **extra_fields) | |
class User(AbstractBaseUser, PermissionsMixin): | |
email = models.EmailField(blank=True, default='', unique=True) | |
name = models.CharField(max_length=200, blank=True, default='') | |
is_active = models.BooleanField(default=True) | |
is_staff = models.BooleanField(default=False) | |
is_superuser = models.BooleanField(default=False) | |
last_login = models.DateTimeField(blank=True, null=True) | |
date_joined = models.DateTimeField(default=timezone.now) | |
objects = CustomUserManager() | |
USERNAME_FIELD = 'email' | |
EMAIL_FIELD = 'email' | |
REQUIRED_FIELDS = [] | |
class Meta: | |
verbose_name = 'User' | |
verbose_name_plural = 'Users' | |
def get_full_name(self): | |
return self.name | |
def get_short_name(self): | |
return self.name | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.conf.urls import include, url | |
from users.views import logout, signup | |
urlpatterns = [ | |
url(r'^accounts/logout/', logout, name='logout'), | |
url(r'^accounts/signup/', signup, name='signup'), | |
url(r'^accounts/', include('django.contrib.auth.urls')), | |
] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.shortcuts import render, redirect | |
from django.contrib.auth import logout as logout_user | |
from django.contrib.auth import login as login_user | |
from .forms import SignUpForm | |
from .models import User | |
def signup(request): | |
form = SignUpForm() | |
if request.method == 'POST': | |
form = SignUpForm(request.POST) | |
if form.is_valid(): | |
user = User.objects.create_user( | |
email=form.cleaned_data['email'], | |
) | |
user.set_password(form.cleaned_data['password']) | |
user.save() | |
login_user(request, user) | |
return redirect('/') | |
return render(request, 'registration/signup.html', { | |
'form': form, | |
}) | |
def logout(request): | |
logout_user(request) | |
return redirect('/') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice, Can you please make an article related to custom user management:-
Send random password to email of user after create any user.
Each user can able to login on same panel with there provided credential.
Use JWT token instead of session
with templates and users app in navbar