Why is a username required for a User?

187 views
Skip to first unread message

Cody Scott

unread,
Apr 8, 2013, 11:09:29 AM4/8/13
to django...@googlegroups.com
To create a User object you need to have a unique username.

I would like to use an email and a password to identify users, since an email is already required for my site's functionality.

It seems silly for a framework so restrict you.


Anderson

unread,
Apr 8, 2013, 11:11:57 AM4/8/13
to django...@googlegroups.com
Hey Cody are using django 1.5?




--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users?hl=en.
For more options, visit https://groups.google.com/groups/opt_out.
 
 



--
Anderson Dias Borges
Senior Analyst Developer

Tu cumprirás o desejo do meu coração se eu Te buscar...
I can't see but I'll take my chances
To hear You call my name

Cody Scott

unread,
Apr 8, 2013, 11:49:56 AM4/8/13
to django...@googlegroups.com
Yes I am using Django 1.5

Anderson

unread,
Apr 8, 2013, 11:56:40 AM4/8/13
to django...@googlegroups.com
You can use BaseUserManager, AbstractBaseUser,PermissionsMixin.
here is a exemple:

from django.db import models
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager
from django.conf    import settings


class MyUserManager(BaseUserManager):
    def create_user(self, email, password=None):
        if not email:
            raise ValueError('Users must have an email address')

        user = self.model(
            email=MyUserManager.normalize_email(email),           
        )
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_superuser(self, email, password): 
        user = self.create_user(email,
            password=password
        )
        user.is_admin = True
        user.save(using=self._db)
        return user

class Users(AbstractBaseUser,PermissionsMixin):
    email             = models.EmailField(verbose_name='email address', max_length=255,unique=True,db_index=True,) 
    name              = models.CharField(verbose_name='Name', max_length=50,blank=True)
    is_active         = models.BooleanField(default=True)
    is_admin         = models.BooleanField(default=False)
    is_customer     = models.BooleanField(default=False)
    datecreated     = models.DateField(auto_now=True)
   
    objects         = MyUserManager()
    USERNAME_FIELD     = 'email'  
    REQUIRED_FIELDS = ['name']
   
    def get_full_name(self):
        return self.email

    def get_short_name(self):      
        return self.email

    def __unicode__(self):
        return self.email

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



Now in your settings you have to add : AUTH_USER_MODEL     = 'auth.Users'






If you want change in ADMIN here the code


from django.contrib import admin
from django import forms
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.forms import ReadOnlyPasswordHashField

from models import Users

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

    class Meta:
        model = Users       

    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(UserCreationForm, self).save(commit=False)
        user.set_password(self.cleaned_data["password1"])
        if commit:
            user.save()
        return user
       
class UserChangeForm(forms.ModelForm):
    password = ReadOnlyPasswordHashField()
    class Meta:
        model = Users

    def clean_password(self):       
        return self.initial["password"]
       
class MyUserAdmin(UserAdmin):
    form         = UserChangeForm
    add_form     = UserCreationForm
  
    list_display = ('email', 'is_admin')
    list_filter = ('is_admin',)
    fieldsets = (
        (None, {'fields': ('email', 'password')}),      
        ('Permissions', {'fields': ('is_admin','groups','user_permissions')}),
        ('Important dates', {'fields': ('last_login',)}),
    )
    add_fieldsets = (
        (None, {
            'classes': ('wide',),
            'fields': ('email', 'password1', 'password2')}
        ),
    )
    search_fields = ('email',)
    ordering = ('email',)
    filter_horizontal = ()

admin.site.register(Users, MyUserAdmin)



Tom Evans

unread,
Apr 8, 2013, 12:16:53 PM4/8/13
to django...@googlegroups.com
On Mon, Apr 8, 2013 at 4:49 PM, Cody Scott <cody.j....@gmail.com> wrote:
> Yes I am using Django 1.5

In 1.5, you can fully customise what fields your User class has. Full
notes in the docs:

https://docs.djangoproject.com/en/1.5/topics/auth/customizing/#auth-custom-user

Cheers

Tom

Cody Scott

unread,
Apr 9, 2013, 9:52:24 AM4/9/13
to django...@googlegroups.com
I placed the code in those places, I put AUTH_USER_MODEL     = 'auth.Users' right after INSTALLED_APPS

"CommandError: One or more models did not validate:
auth.user: Model has been swapped out for 'auth.Users' which has not been installed or is abstract.
admin.logentry: 'user' has a relation with model auth.Users, which has either not been installed or is abstract."

Vignesh Sunder

unread,
Apr 9, 2013, 10:05:33 AM4/9/13
to django...@googlegroups.com
Is your new 'Users' class defined in an 'auth' module/app inside your project?

I guess the problem here is that you are supposed to refer to the module containing the 'models.py' in which you have defined 'Users' class.

For example, if your module/app is 'mysite' and you have defined 'Users' class in 'mysite/models.py', then your settings.AUTH_USER_MODEL should be 'mysite.Users'

Cody Scott

unread,
Apr 9, 2013, 10:24:19 AM4/9/13
to django...@googlegroups.com
Thank you that was my issue. Now syncdb works I also needed to add a name parameter to create_superuser and create_user and make sure create_super user has the name in the call to self.create_user

I see h

Cody Scott

unread,
Apr 9, 2013, 10:28:42 AM4/9/13
to django...@googlegroups.com
Except the super user I created with syncdb doesn't have access to anything


On Tuesday, 9 April 2013 10:24:19 UTC-4, Cody Scott wrote:
Thank you that was my issue. Now syncdb works I also needed to add a name parameter to create_superuser and create_user and make sure create_super user has the name in the call to self.create_user


Cody Scott

unread,
Apr 9, 2013, 11:05:07 AM4/9/13
to django...@googlegroups.com
In models.py in /django/contrib/auth there is a 

u.is_superuser = True

but when I add it just like how is_staff and is_active are added I get the error 

"FieldError: Local field 'is_superuser' in class 'Users' clashes with field of similar name from base class 'PermissionsMixin'

Cody Scott

unread,
Apr 9, 2013, 11:22:14 AM4/9/13
to django...@googlegroups.com
In the docs https://docs.djangoproject.com/en/1.5/topics/auth/customizing/#custom-users-and-django-contrib-admin

It says to use with admin you need the following methods 
is_active, has_perm, has_module_perms

So I added them but I don't really understand how to do permissions

Here is the code I put in Users
   
    def __unicode__(self):
        return self.email

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

    #start of new code
    def is_active(self):
        return self.is_active

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

    def has_module_perms(self, app_label):
        return True


--
You received this message because you are subscribed to a topic in the Google Groups "Django users" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/django-users/zAMBjf6WmFU/unsubscribe?hl=en.
To unsubscribe from this group and all its topics, send an email to django-users...@googlegroups.com.

Anderson

unread,
Apr 9, 2013, 11:28:40 AM4/9/13
to django...@googlegroups.com
You don't have to worry about permissions all these methods come with PermissionsMixin and is_superuser too.
https://docs.djangoproject.com/en/1.5/topics/auth/customizing/#auth-custom-user

Do not override those methods otherwise all users will return always true.


--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.

To post to this group, send email to django...@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users?hl=en.
For more options, visit https://groups.google.com/groups/opt_out.
 
 

Cody Scott

unread,
Apr 9, 2013, 11:46:39 AM4/9/13
to django...@googlegroups.com
If I don't have them and I log in to admin I get
"You don't have permission to edit anything."

Anderson

unread,
Apr 9, 2013, 11:56:00 AM4/9/13
to django...@googlegroups.com
No . inside has_perm before check  whether you have permission or not is going to check if you are active and superuser.

# Active superusers have all permissions.
if self.is_active and self.is_superuser:
        return True

Cody Scott

unread,
Apr 9, 2013, 12:04:41 PM4/9/13
to django...@googlegroups.com
OK so how do I access the admin then?

Cody Scott

unread,
Apr 9, 2013, 12:35:36 PM4/9/13
to django...@googlegroups.com
Okay Anderson you were right I didn't need those methods. All I needed was 
user.is_superuser = True
after
user.is_admin = True

Thanks again for the code!
Reply all
Reply to author
Forward
0 new messages