Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # -*- coding: utf-8 -*-
- u"""Classes for extended Django user model."""
- from django.contrib.auth.models import AbstractBaseUser
- from django.contrib.auth.models import BaseUserManager
- from django.contrib.auth.models import PermissionsMixin
- from django.db import models
- class UserManager(BaseUserManager):
- u"""Default class for models managing."""
- def create_user(self, email, password=None):
- u"""
- Create ExtUser. Email (default) is required.
- You can override required field here and in ExtUser model.
- """
- if not email:
- raise ValueError('Email is required.')
- user = self.model(
- email=UserManager.normalize_email(email),
- )
- user.set_password(password)
- user.save(using=self._db)
- return user
- def create_superuser(self, email, password):
- u"""Create superuser."""
- user = self.create_user(email, password)
- user.is_admin = True
- user.is_superuser = True
- user.save(using=self._db)
- return user
- class ExtUser(AbstractBaseUser, PermissionsMixin):
- u"""
- Default ExtUser model for replacing default User model.
- You must make all changes, definition additional fields and other here.
- """
- email = models.EmailField(
- 'Email',
- max_length=255,
- unique=True,
- db_index=True
- )
- username = models.CharField(
- 'First name',
- max_length=40,
- null=True,
- blank=True
- )
- register_date = models.DateField(
- 'Registration date',
- auto_now_add=True
- )
- is_active = models.BooleanField(
- 'Active', # Not blocked, banned, etc
- default=True
- )
- is_admin = models.BooleanField(
- 'Is superuser',
- default=False
- )
- # Django require define this method
- def get_full_name(self):
- return self.email
- @property
- def is_staff(self):
- # Required Django for admin panel
- return self.is_admin
- def get_short_name(self):
- u"""Return short name."""
- return self.email
- def __str__(self):
- u"""String representation of model. Email by default."""
- return self.email
- # Field, used as 'username' in authentication and other forms
- USERNAME_FIELD = 'email'
- """
- Username required by default. Add here another fields, where
- must be defined for correct model creation.
- """
- REQUIRED_FIELDS = []
- # Link model and model manager
- objects = UserManager()
- class Meta:
- verbose_name = 'user'
- verbose_name_plural = 'users'
- db_table = 'extuser'
- u"""Used in admin panel and for initialization."""
- from django.contrib import admin
- from django.contrib.auth.admin import UserAdmin
- from django.contrib.auth.models import Group
- from .forms import UserChangeForm
- from .forms import UserCreationForm
- from .models import ExtUser
- class UserAdmin(UserAdmin):
- """
- Base admin class.
- form - form for change user settings.
- add_form - used for create users
- """
- form = UserChangeForm
- add_form = UserCreationForm
- # Fields listed in admin panel
- list_display = [
- 'email',
- 'username',
- 'is_admin',
- ]
- # Filter for admin panel
- list_filter = ('is_admin',)
- # Fieldsets for ordering and grouping
- fieldsets = (
- (None, {'fields': ('email', 'password', 'username')}),
- ('Permissions', {'fields': ('is_admin',)}),
- ('Important dates', {'fields': ('last_login',)}),
- )
- add_fieldsets = (
- (None, {
- 'classes': ('wide',),
- 'fields': (
- 'email',
- 'password1',
- 'password2'
- )}
- ),
- )
- search_fields = ('email',)
- ordering = ('email',)
- filter_horizontal = ()
- # Register ExtUser admin panel in Django
- admin.site.register(ExtUser, UserAdmin)
- admin.site.unregister(Group)
- from django import forms
- from django.contrib.auth.forms import ReadOnlyPasswordHashField
- from django.contrib.auth import get_user_model
- class UserCreationForm(forms.ModelForm):
- password1 = forms.CharField(
- label='Пароль',
- widget=forms.PasswordInput
- )
- password2 = forms.CharField(
- label='Подтверждение',
- widget=forms.PasswordInput
- )
- def clean_password2(self):
- password1 = self.cleaned_data.get('password1')
- password2 = self.cleaned_data.get('password2')
- if password1 and password2 and password1 != password2:
- raise forms.ValidationError('Пароль и подтверждение не совпадают')
- return password2
- def save(self, commit=True):
- user = super(UserCreationForm, self).save(commit=False)
- user.set_password(self.cleaned_data['password1'])
- if commit:
- user.save()
- return user
- class Meta:
- model = get_user_model()
- fields = ('email',)
- class UserChangeForm(forms.ModelForm):
- password = ReadOnlyPasswordHashField(
- widget=forms.PasswordInput,
- required=False
- )
- def save(self, commit=True):
- user = super(UserChangeForm, self).save(commit=False)
- password = self.cleaned_data["password"]
- if password:
- user.set_password(password)
- if commit:
- user.save()
- return user
- class Meta:
- model = get_user_model()
- fields = ['email', ]
- class LoginForm(forms.Form):
- """Форма для входа в систему
- """
- username = forms.CharField()
- password = forms.CharField()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement