Skip to content

Instantly share code, notes, and snippets.

@xpostudio4
Last active December 29, 2015 13:59
Show Gist options
  • Save xpostudio4/7680855 to your computer and use it in GitHub Desktop.
Save xpostudio4/7680855 to your computer and use it in GitHub Desktop.
Custom User Model Django
#models.py
#Stdlib imports
import datetime
#Django core Imports
from django.db import models
from django.contrib.auth.models import (
BaseUserManager, AbstractBaseUser, PermissionsMixin
)
#Third party Libraries
from templated_email import send_templated_mail
# Create your models here.
class AppUserManager(BaseUserManager):
def create_user(self, email, first_name, last_name, password=None):
"""
Creates and saves a User with the given email, first_name, last_name
and password.
"""
if not email:
raise ValueError('Todo usuario debe tener un email')
user = self.model(
email = AppUserManager.normalize_email(email),
first_name = first_name,
last_name = last_name
)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, first_name, last_name, password):
"""
Creates and saves a Superuser with the given email, first_name, last_name
and password.
"""
user = self.create_user(email,
first_name=first_name,
last_name=last_name,
password=password
)
user.is_admin = True
user.save(using=self._db)
return user
class UserProfile(AbstractBaseUser):
email = models.EmailField(
verbose_name="Correo Electronico",
max_length=255,
unique=True,
db_index=True
)
first_name = models.CharField(max_length=40, verbose_name="Nombre")
last_name = models.CharField(max_length=40, verbose_name="Apellido")
picture = models.ImageField(upload_to="profile_pics", blank=True)
phone = models.CharField(max_length=10,null=True, blank=True)
is_phone_visible = models.BooleanField(default=False,verbose_name="Desea que el telefono se vea en sus anuncios")
address = models.TextField(null=True, blank=True, verbose_name="Direccion")
#about = models.TextField(null=True, blank=True, verbose_name="MiniBio")
is_address_visible = models.BooleanField(default=False, verbose_name="Desea que su direccion se vea en los anuncios")
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
objects = AppUserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['first_name', 'last_name']
def get_full_name(self):
return self.first_name + " " + self.last_name
def get_short_name(self):
#The user is identified by their email address
return self.email
def __unicode__(self):
return self.email
def save(self, *args, **kwargs):
if not self.id:
send_templated_mail(
template_name='user_creation',
from_email='[email protected]',
recipient_list = [self.email],
context={
'username': self.email,
'full_name': self.get_full_name,
'signup_date': datetime.datetime.today(),
},
)
super(UserProfile, self).save(*args, **kwargs)
def has_perm(self, perm, obj=None):
"Does the user have a specific permission?"
# Simplest possible answer: Yes, always
return True
def has_module_perms(self, app_label):
"Does the user have permissions to view the app `app_label`?"
# Simplest possible answer: Yes, always
return True
@property
def is_staff(self):
"Is the user a member of staff?"
# Simplest possible answer: All admins are staff
return self.is_admin
#forms.py
#Core Django Imports
from django import forms
from django.contrib.auth.models import Group
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.forms import ReadOnlyPasswordHashField, AuthenticationForm
#Third party apps
from captcha.fields import CaptchaField
#Project apps import
from .models import UserProfile
class UserProfileCreationForm(forms.ModelForm):
"""A form for creating new users. Includes all the required
fields, plus a repeated password."""
form_fields = ['password1','password2', 'email', 'first_name', 'last_name','picture',
'phone','is_phone_visible', 'address', 'is_address_visible',
]
password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput)
captcha = CaptchaField()
class Meta:
model = UserProfile
fields = ('email', 'first_name', 'last_name','picture',
'phone','is_phone_visible', 'address', 'is_address_visible',
)
def clean_password2(self):
# Check that the two password entries match
password1 = self.cleaned_data.get("password1")
password2 = self.cleaned_data.get("password2")
if password1 and password2 and password1 != password2:
raise forms.ValidationError("Passwords don't match")
return password2
def __init__(self, *args, **kwargs):
super(UserProfileCreationForm, self).__init__(*args, **kwargs)
#change the html class of all the elements of the form to get bootstrap 3 styling
for field in self.form_fields:
self.fields[field].widget.attrs.update({'class':'form-control'})
def save(self, commit=True):
# Save the provided password in hashed format
user = super(UserProfileCreationForm, self).save(commit=False)
user.set_password(self.cleaned_data["password1"])
if commit:
user.save()
return user
class UserProfileChangeForm(forms.ModelForm):
"""A form for updating users. Includes all the fields on
the user, but replaces the password field with admin's
password hash display field.
"""
password = ReadOnlyPasswordHashField()
class Meta:
model = UserProfile
def clean_password(self):
# Regardless of what the user provides, return the initial value.
# This is done here, rather than on the field, because the
# field does not have access to the initial value
return self.initial["password"]
class UserProfileLoginForm(AuthenticationForm):
"""A Form for user login."""
form_fields = ["username", "password"]
username = forms.CharField(max_length=254, label="Correo Electronico")
def __init__(self, *args, **kwargs):
super(AuthenticationForm, self).__init__(*args, **kwargs)
#change the html class of all the elements of the form to get bootstrap 3 styling
for field in self.form_fields:
self.fields[field].widget.attrs.update({'class':'form-control'})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment