I can not create a new user via admin Django?

28 views
Skip to first unread message

setivo...@gmail.com

unread,
Mar 10, 2016, 7:55:19 AM3/10/16
to Django users

I create project with my authuser model where login via email, not through name

--------------------------------

Models.py
----------------------------


import imghdr
import string
import datetime

from django_countries.fields import CountryField

from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin
from django.core.urlresolvers import reverse
from django.core.exceptions import ValidationError
from django.core.validators import MinLengthValidator
from django.conf import settings

from libs.validators import OnlyLowercaseAndDigits


ALLOWED_CHARS = string.ascii_lowercase + string.digits
MAX_LENGTH = 8


class AccountUserManager(BaseUserManager):
    """
    Manager for my user model
    """

    def create_user(self, email, name, password=None):
        """
        Creates and saves a user with the given email, name of account and password.
        """
        if not email:
            raise ValueError('User must have an email address')
        if not name:
            raise ValueError('User must have a name of account')
        user = self.model(email=self.normalize_email(email), name=name)
        user.set_password(password)
        user.save()
        return user

    def create_superuser(self, email, name, password):
        """
        Creates and saves a superuser with the given email, name of account and password.
        """
        if not password:
            raise ValueError('Superuser must be have a password')
        user = self.create_user(email=self.normalize_email(email), name=name, password=password)
        user.is_superuser = True
        user.save()
        return user

    def make_random_password(self, length=10, allowed_chars=ALLOWED_CHARS):
        return super().make_random_password(length, allowed_chars)


class AccountUser(AbstractBaseUser, PermissionsMixin):
    """
    Model for users, registering by email and unique name of account
    """

    email = models.EmailField('Email of account', max_length=50, unique=True)
    name = models.CharField('Account of name', max_length=50, validators=[
        OnlyLowercaseAndDigits,
        MinLengthValidator(MAX_LENGTH, 'Field must be at least {0} chars'.format(MAX_LENGTH)),
    ])
    is_active = models.BooleanField(default=True)
    date_joined = models.DateTimeField('Date joined', auto_now_add=True)

    objects = AccountUserManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['name']

    class Meta:
        db_table = 'account_user'
        verbose_name = "AccountUser"
        verbose_name_plural = "AccountUsers"
        get_latest_by = 'date_joined'
        ordering = ['-date_joined']

    def __str__(self):
        return '{0.email}'.format(self)

    def save(self, *args, **kwargs):
        try:
            self.full_clean()
        except ValidationError as errors_message:
            print('Was happened next errors:\n-----------------------------')
            for error in errors_message:
                print(error)
        else:
            super().save(*args, **kwargs)
            account = AccountUser.objects.get(email=self.email)
            if not hasattr(account, 'accountuserinfo'):
                AccountUserInfo.objects.create(account=account)

    def get_absolute_url(self):
        return reverse('app_accounts:account_profile')

    def get_full_name(self):
        return '{0.name} ({0.email})'.format(self)

    def clean(self):
        if len(self.password) < MAX_LENGTH:
            raise ValidationError({
                'password': 'Length of password must be at least {0}'.format(MAX_LENGTH)
            })
        if all(i in string.digits for i in self.password):
            raise ValidationError({
                'password': 'Your password can\'t be entirely numeric'
            })

    def get_short_name(self):
        return '{0.email}'.format(self)

    @property
    def is_staff(self):
        return self.is_superuser

    def all_dictionaries_created_user(self):
        count_translators = self.translators.count()
        count_glossaries = self.glossaries.count()
        if any([count_translators, count_glossaries]):
            result = 'User have: translators - {0}; glossaries - {1}.'.format(count_translators, count_glossaries)
        else:
            result = 'User have not nothing!!!'
        return result

    def last_created_dictionaries(self, types_dictionaries=['translators', 'glossaries']):
        result = list()
        for type_dictionary in types_dictionaries:
            if type_dictionary == 'translators':
                created_translators = self.translators.all()[:3]
                if created_translators:
                    result.append('User have next translators: {0}'.format(created_translators))
                else:
                    result.append('User have not translators')
            if type_dictionary == 'glossaries':
                created_glossaries = self.glossaries.all()[:3]
                if created_glossaries:
                    result.append('User have next glossaires: {0}'.format(created_glossaries))
                else:
                    result.append('User have not glossaires')
        return result

--------------------------------------------------------

Forms.py

--------------------

# For admin interface

class FormAccountUserCreation(forms.ModelForm):
    """A form for creating new users. Includes all the required
    fields, plus a repeated password."""

    password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
    password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput)

    class Meta:
        model = AccountUser
        fields = ('email', 'password')

    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 save(self, commit=True):
        # Save the provided password in hashed format
        user = super(FormAccountUserCreation, self).save(commit=False)
        user.set_password(self.cleaned_data["password1"])
        if commit:
            user.save()
        return user


class FormAccountUserChange(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 = AccountUser
        fields = ('email', 'name', 'password', 'is_active', 'is_superuser')

    def clean_password(self):
        return self.initial.get('password')

----------------------------

 Traceback: http://dpaste.com/3Z2TMJB 


And I do not know how change text in login page admin Django from "Forgotten your password or username?" to "Forgotten your password or email?"




Reply all
Reply to author
Forward
0 new messages