Django custom user

173 views Asked by At

I created custom user

class CoinUser(AbstractBaseUser):
username = models.CharField(_('username'), max_length=30, unique=True,
    help_text=_('Required. 30 characters or fewer. Letters, numbers and @/./+/-/_ characters'),
    validators=[
      validators.RegexValidator(re.compile('^[\w.@+-]+$'), _('Enter a valid username.'), _('invalid'))
    ])
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)    
first_name = models.CharField(_('first name'), max_length=30, blank=True, null=True)
patronymic = models.CharField(_('patronymic'), max_length=30,
    help_text=_('Required. 30 characters or fewer. Letters, numbers and @/./+/-/_ characters'))
last_name = models.CharField(_('last name'), max_length=30, blank=True, null=True)
email = models.EmailField(_('email address'), max_length=255, unique=True, 
    validators=[
      validators.RegexValidator(re.compile('^.+@.+\..+$', flags=re.IGNORECASE), _('Enter a valid email.'), _('invalid'))
    ])
post_code = models.CharField(_('post code'), max_length=10)
is_staff = models.BooleanField(_('staff status'), default=False,
    help_text=_('Designates whether the user can log into this admin site.'))
is_active = models.BooleanField(_('active'), default=False,
    help_text=_('Designates whether this user should be treated as active. Unselect this instead of deleting accounts.'))
date_joined = models.DateTimeField(_('date joined'), default=timezone.now)
phone = models.CharField(_('phone number'), max_length=12, blank=True, null=True, unique=True,
    validators=[
      validators.RegexValidator(re.compile('^[0-9]{12,12}$', flags=re.IGNORECASE), _('Enter a valid phone number.'), _('invalid'))
    ])

objects = CoinUserManager()

USERNAME_FIELD = 'username'        
REQUIRED_FIELDS = ['email', 'phone']

def get_full_name(self):
    full_name = '%s %s' % (self.first_name, self.last_name)
    return full_name.strip()

def get_short_name(self):
    return self.first_name

def __str__(self):
    return self.username

def has_perm(self, perm, obj=None):
    return True

def has_module_perms(self, app_label):
    return True
@property
def is_staff(self):
    return self.is_admin
class Meta:
    managed = True
    db_table = "co_user"
    verbose_name = _("Coin user")
    verbose_name_plural = _("Coin users")

then I created UserAdmin

class CoinUserAdmin(UserAdmin):

form = UserChangeFrom
add_form = UserCreationForm

list_display = ('email', 'username', 'phone')
list_filter = ('is_admin',)
fieldsets = (
    (None, {'fields': ('username',)}),
    ('Contact info', {'fields':('email','phone')}),
)
search_fields = ('username', 'email', 'phone')
ordering = ('username', 'email',)
filter_horizontal = ()

and added UserCreationForm

class  UserCreationForm(forms.ModelForm):
"""docstring for  UserCreationForm"""
password1 = forms.CharField(label=_('Password'), widget=forms.PasswordInput)
password2 = forms.CharField(label=_('Password confirmation'), widget=forms.PasswordInput)

class Meta:
    model = CoinUser
    fields = ('email', 'password', 'username', 'phone')

def clean_password2(self):
    #Check that two password entires 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(UserCreationForm, self).save(commit=False)
    # user.phone = self.cleaned_data["phone"]
    user.set_password(self.cleaned_data["password1"])
    if commit:
        user.save()
    return user

It works fine but when I tried to add email and phone

email = forms.CharField(label=_("Email"), widget=forms.EmailField)
phone = forms.CharField(label=_("Phone number"), widget=forms.TextInput)

fields to UserCreationForm they didn't view and when I tried to save my user without these field I got error "'EmailField' object has no attribute 'value_from_datadict'"

1

There are 1 answers

1
likeon On

EmailField actually is form field. Try to use EmailInput widget.