开发者

Django registration, first and last names, no username

I am using the django-registration package. I do not want people to have a username but to enter instead their first a开发者_如何学Cnd last names. Like on Facebook. How can I do that ?


Django auth (and by extension admin) requires a username - full stop. So you'll have to go to some effort to work around that.

You have a few issues to consider: 1) Firstname Lastname will rapidly lead to collisions. What does your service do when the second "John Smith" wants to sign up?

2) You have to create a username, so you'll likely use a hash of firstname_lastname. Again, what do you do when you get a second exact match?

3) You'll have to write a custom auth backend to take care of the login, this isn't actually that hard.

A prototype of the solution to #2 can be found here - basically in the form processing, generate a random unique hash.

while True:
    self.cleaned_data['username'] = str(md5(str(self.data['email']) + str(random.random())).hexdigest())[0:30]
    try:
        user = User.objects.get(username__iexact=self.cleaned_data['username'])
    except User.DoesNotExist:
        break


You need to define your own AUTHENTICATION_BACKEND and declare it in settings.py : ie :

AUTHENTICATION_BACKENDS = (
    'yourapp.backends.NoUsernameModelBackend',
)

The code should look like this :

class NoUsernameModelBackend
    def authenticate(self, first_name=None,last_name, password=None):
        try:
            user = User.objects.get(first_name=first_name,last_name=last_name)
            if user.check_password(password):
            return user
        except User.DoesNotExist:        
            return None

    def get_user(self, user_id):
        try:
            return User.objects.get(pk=user_id)
        except User.DoesNotExist:
            return None

Then you need to define your own AuthenticationForm to take a first_name and a last_name instead of a username and define the url pattern accordingly.

in urls :

(r'^login/?$','django.contrib.auth.views.login', {'authentication_form':'FullNameAuthenticationForm'}, 'login'),
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜