bgarcial

Creating Django users with just an email and password

Jul 13th, 2017
554
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.75 KB | None | 0 0
  1. # models.py
  2.  
  3. from django.contrib.auth.models import BaseUserManager
  4. from django.contrib.auth.models import AbstractBaseUser
  5. from django.contrib.auth.models import PermissionsMixin
  6. from django.utils.translation import ugettext_lazy as _
  7.  
  8. class UserManager(BaseUserManager):
  9.     def _create_user(self, email, password, **extra_fields):
  10.         """
  11.        Creates and saves a User with the given email and password.
  12.        """
  13.         if not email:
  14.             raise ValueError("Users must have an email address")
  15.             email = self.normalize_email(email)
  16.             user = self.model(email = email, **extra_fields)
  17.             user.set_password(password)
  18.             user.save()
  19.             return user
  20.  
  21.     def create_superuser(self, email, password, **extra_fields):
  22.         extra_fields.setdefault('is_staff', True)
  23.         extra_fields.setdefault('is_superuser', True)
  24.         extra_fields.setdefault('is_active', True)
  25.  
  26.         if extra_fields.get('is_staff') is not True:
  27.             raise ValueError('Superuser must have is_staff=True.')
  28.         if extra_fields.get('is_superuser') is not True:
  29.             raise ValueError('Superuser must have is_superuser=True.')
  30.         return self._create_user(email, password, **extra_fields)
  31.  
  32. class User(AbstractBaseUser, PermissionsMixin):
  33.  
  34.     # I had add the username field despite that I don't use in my User model
  35.     username = models.CharField(_('username'), max_length=30, null=True,
  36.             help_text=_('Required. 30 characters or fewer. Letters, digits and ''@/./+/-/_ only.'),
  37.         validators=[RegexValidator(r'^[\w.@+-]+$', _('Enter a valid username.'), 'invalid')
  38.         ])
  39.  
  40.     email = models.EmailField(unique=True, null=True,
  41.             help_text=_('Required. Letters, digits and ''@/./+/-/_ only.'),
  42.         validators=[RegexValidator(r'^[\w.@+-]+$', _('Enter a valid email address.'), 'invalid')
  43.         ])
  44.  
  45.     is_staff = models.BooleanField(
  46.         _('staff status'),
  47.         default=False,
  48.         help_text=_('Designates whether the user can log into this site.'),
  49.     )
  50.  
  51.     is_active = models.BooleanField(
  52.         _('active'),
  53.         default=True,
  54.         help_text=_(
  55.             'Designates whether this user should be treated as active. '
  56.             'Unselect this instead of deleting accounts.'
  57.         ),
  58.     )
  59.  
  60.     objects = UserManager()
  61.     USERNAME_FIELD = "email"
  62.  
  63.     class Meta:
  64.         db_table = 'auth_user'
  65.         verbose_name_plural = 'Usuarios en la plataforma'
  66.  
  67.     def __str__(self):
  68.         return "@{}".format(self.email)
  69.  
  70.  
  71. # forms.py
  72.  
  73. rom django.contrib.auth import get_user_model
  74. from django.contrib.auth.forms import UserChangeForm, UserCreationForm
  75. from django import forms
  76.  
  77.  
  78. class CustomUserChangeForm(UserChangeForm):
  79.     class Meta(UserChangeForm.Meta):
  80.         model = get_user_model()
  81.  
  82.  
  83. class CustomUserCreationForm(UserCreationForm):
  84.     class Meta(UserCreationForm.Meta):
  85.         model = get_user_model()
  86.         # I specify the email field to the create user
  87.         fields = ('email',)
  88.  
  89.  
  90. class UserCreateForm(UserCreationForm):
  91.  
  92.     class Meta:
  93.         fields = ("email", "password1", "password2",)
  94.         model = get_user_model()
  95.  
  96.     def __init__(self, *args, **kwargs):
  97.         super().__init__(*args, **kwargs)
  98.         self.fields["email"].label = "Email address"
  99.  
  100.  
  101.  
  102. # admin.py
  103.  
  104.  
  105. from __future__ import unicode_literals
  106. from django.contrib import admin
  107.  
  108. from django.contrib.auth.admin import UserAdmin
  109.  
  110. from .models import User
  111. from .forms import CustomUserChangeForm, CustomUserCreationForm
  112.  
  113.  
  114. # Inherit of the original UserAdmin for use the customized forms
  115. class CustomUserAdmin(UserAdmin):
  116.     form = CustomUserChangeForm
  117.     add_form = CustomUserCreationForm
  118.  
  119.     fieldsets = UserAdmin.fieldsets + (
  120.         (
  121.             None, {
  122.                 'classes':('wide',),
  123.                 'fields':(
  124.                     'slug',
  125.                     #'first_name',
  126.                     #'last_name',
  127.                     'display_name',
  128.                     'gender',
  129.                     'country_of_origin',
  130.                     'city_of_origin',
  131.                     'country_current_residence',
  132.                     'city_current_residence',
  133.                     'speak_languages',
  134.                     #'email',
  135.                     'phone_number',
  136.                     'address',
  137.                     'bio',
  138.                     'avatar',
  139.                     'date_of_birth',
  140.                     'is_student',
  141.                     'is_professor',
  142.                     'is_executive',
  143.                     'is_study_host',
  144.                     'is_innovation_host',
  145.                     'is_hosting_host',
  146.                     'is_entertainment_host',
  147.                     'is_other_services_host',
  148.                 ),
  149.             }
  150.         ),
  151.     )
  152.     # exclude = ('first_name', 'last_name')
  153.  
  154. # Change our UserAdmin class to inherit of our CustomUserAdmin created above (do not inherit of model.ModelAdmin)
  155.  
  156. @admin.register(User)
  157. class UserAdmin(CustomUserAdmin):
  158.  
  159.     list_display = ('id',
  160.                     'email',
  161.                     'slug',
  162.                     'first_name',
  163.                     'last_name',
  164.                     'gender',
  165.                     'country_of_origin',
  166.                     'phone_number',
  167.                     'address',
  168.                     'bio',
  169.                     'date_of_birth',
  170.                     'is_student',
  171.                     'is_professor',
  172.                     'is_executive',
  173.                     'is_study_host',
  174.                     "is_innovation_host",
  175.                     "is_hosting_host",
  176.                     "is_entertainment_host",
  177.                     "is_other_services_host",
  178.     )
  179.  
  180.  
  181. # settings.py
  182. AUTH_USER_MODEL = ‘my_app_name.User
Advertisement
Add Comment
Please, Sign In to add comment