Django注册:电子邮件用户名 [英] Django-Registration: Email as username
问题描述
如何使用电子邮件代替使用用户名进行身份验证,请使用 django-registration 。
How do I use emails instead of username for authentication using django-registration.
一旦我已经安装了注册模块,我该如何执行此更改。
Further how do I enforce this change once I have already installed the registration module.
我是否在这里编辑解决方案任何人都知道一个很好的黑客使django注册使用电子邮件作为用户名?在lib文件夹?
Do I edit the solution here Anyone knows a good hack to make django-registration use emails as usernames? in the lib folder?
推荐答案
亲爱的Django Coder,
Dear fellow Django Coder,
我认为这是最好的办法祝你好运!
I think this is the best way to do it. Good luck!
第一步是创建您要使用的表单。
项目/ accounts / forms.py
from django import forms
from registration.forms import RegistrationForm
from django.contrib.auth.models import User
class Email(forms.EmailField):
def clean(self, value):
super(Email, self).clean(value)
try:
User.objects.get(email=value)
raise forms.ValidationError("This email is already registered. Use the 'forgot password' link on the login page")
except User.DoesNotExist:
return value
class UserRegistrationForm(forms.Form):
password1 = forms.CharField(widget=forms.PasswordInput(), label="Password")
password2 = forms.CharField(widget=forms.PasswordInput(), label="Repeat your password")
#email will be become username
email = Email()
def clean_password(self):
if self.data['password1'] != self.data['password2']:
raise forms.ValidationError('Passwords are not the same')
return self.data['password1']
在这里,您正在创建一个文件来覆盖django注册中的register()函数。
project / accounts / regbackend.py
project/accounts/regbackend.py
from django.conf import settings
from django.contrib.sites.models import RequestSite
from django.contrib.sites.models import Site
from registration import signals
from registration.forms import RegistrationForm
from registration.models import RegistrationProfile
from registration.backends import default
class Backend(default.DefaultBackend):
def register(self, request, **kwargs):
email, password = kwargs['email'], kwargs['password1']
username = email
if Site._meta.installed:
site = Site.objects.get_current()
else:
site = RequestSite(request)
new_user = RegistrationProfile.objects.create_inactive_user(username, email,
password, site)
signals.user_registered.send(sender=self.__class__,
user=new_user,
request=request)
return new_user
将您的网址引导到您要使用的路径。 >
Direct your urls to paths you want to use.
项目/ urls.py
(r'^accounts/', include('registration.backends.default.urls')),
告诉您的网址使用自定义后端进行注册视图。另外,导入您创建的表单,并将其添加到要由视图处理的URL。
项目/ accounts / urls.py
from django.conf.urls.defaults import *
from registration.backends.default.urls import *
from accounts.forms import UserRegistrationForm
urlpatterns += patterns('',
#customize user registration form
url(r'^register/$', 'registration.views.register',
{
'backend': 'accounts.regbackend.Backend',
'form_class' : UserRegistrationForm
},
name='registration_register'
),
)
希望有效!
-Matt
这篇关于Django注册:电子邮件用户名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!