有没有一种很好的方法在django中执行此操作而不必滚动我自己的身份验证系统?我希望用户名是用户的电子邮件地址,而不是他们创建用户名。
请告知,谢谢。
答案 0 :(得分:34)
对于其他任何想要这样做的人,我建议您查看django-email-as-username这是一个非常全面的解决方案,其中包括修补管理员和createsuperuser
管理命令以及其他位和碎片。
修改:从Django 1.5开始,您应该考虑使用custom user model代替django-email-as-username。
答案 1 :(得分:27)
这就是我们的工作。它不是一个“完整”的解决方案,但它可以满足您的需求。
from django import forms
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User
class UserForm(forms.ModelForm):
class Meta:
model = User
exclude = ('email',)
username = forms.EmailField(max_length=64,
help_text="The person's email address.")
def clean_email(self):
email = self.cleaned_data['username']
return email
class UserAdmin(UserAdmin):
form = UserForm
list_display = ('email', 'first_name', 'last_name', 'is_staff')
list_filter = ('is_staff',)
search_fields = ('email',)
admin.site.unregister(User)
admin.site.register(User, UserAdmin)
答案 2 :(得分:21)
这是一种方法,可以接受用户名和电子邮件:
from django.contrib.auth.forms import AuthenticationForm
from django.contrib.auth.models import User
from django.core.exceptions import ObjectDoesNotExist
from django.forms import ValidationError
class EmailAuthenticationForm(AuthenticationForm):
def clean_username(self):
username = self.data['username']
if '@' in username:
try:
username = User.objects.get(email=username).username
except ObjectDoesNotExist:
raise ValidationError(
self.error_messages['invalid_login'],
code='invalid_login',
params={'username':self.username_field.verbose_name},
)
return username
不知道是否有一些设置来设置默认的身份验证表单,但您也可以覆盖urls.py中的网址
url(r'^accounts/login/$', 'django.contrib.auth.views.login', { 'authentication_form': EmailAuthenticationForm }, name='login'),
提交ValidationError会在提交无效电子邮件时阻止500错误。使用super的“invalid_login”定义会使错误消息不明确(与特定的“找不到该电子邮件的用户”相比),这样可以防止泄露是否为您的服务上的帐户注册了电子邮件地址。如果您的架构中的信息不安全,那么获得更多信息性错误消息可能会更友好。
答案 3 :(得分:8)
Django现在提供了一个包含管理员和表单的扩展身份验证系统的完整示例:https://docs.djangoproject.com/en/stable/topics/auth/customizing/#a-full-example
您基本上可以复制/粘贴它并进行调整(在我的情况下我不需要date_of_birth
)。
从Django 1.5开始实际可用,到现在仍然可用(django 1.7)。
答案 4 :(得分:7)
如果您要扩展用户模型,则无论如何都必须实现自定义用户模型。
以下是Django 1.8的示例。 Django 1.7需要更多的工作,主要是更改默认表单(只需查看UserChangeForm
中的UserCreationForm
& django.contrib.auth.forms
- 这就是1.7中所需的内容。
user_manager.py:
from django.contrib.auth.models import BaseUserManager
from django.utils import timezone
class SiteUserManager(BaseUserManager):
def create_user(self, email, password=None, **extra_fields):
today = timezone.now()
if not email:
raise ValueError('The given email address must be set')
email = SiteUserManager.normalize_email(email)
user = self.model(email=email,
is_staff=False, is_active=True, **extra_fields)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, password, **extra_fields):
u = self.create_user(email, password, **extra_fields)
u.is_staff = True
u.is_active = True
u.is_superuser = True
u.save(using=self._db)
return u
models.py:
from mainsite.user_manager import SiteUserManager
from django.contrib.auth.models import AbstractBaseUser
from django.contrib.auth.models import PermissionsMixin
class SiteUser(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(unique=True, blank=False)
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
is_staff = models.BooleanField(default=False)
USERNAME_FIELD = 'email'
objects = SiteUserManager()
def get_full_name(self):
return self.email
def get_short_name(self):
return self.email
forms.py:
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.forms import UserChangeForm, UserCreationForm
from mainsite.models import SiteUser
class MyUserCreationForm(UserCreationForm):
class Meta(UserCreationForm.Meta):
model = SiteUser
fields = ("email",)
class MyUserChangeForm(UserChangeForm):
class Meta(UserChangeForm.Meta):
model = SiteUser
class MyUserAdmin(UserAdmin):
form = MyUserChangeForm
add_form = MyUserCreationForm
fieldsets = (
(None, {'fields': ('email', 'password',)}),
('Permissions', {'fields': ('is_active', 'is_staff', 'is_superuser',)}),
('Groups', {'fields': ('groups', 'user_permissions',)}),
)
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('email', 'password1', 'password2')}
),
)
list_display = ('email', )
list_filter = ('is_active', )
search_fields = ('email',)
ordering = ('email',)
admin.site.register(SiteUser, MyUserAdmin)
settings.py:
AUTH_USER_MODEL = 'mainsite.SiteUser'
答案 5 :(得分:2)
其他替代方案对我来说看起来过于复杂,因此我编写了一个允许使用用户名,电子邮件或两者进行身份验证的代码段,并启用或禁用区分大小写。我将其上传到pip django-dual-authentication。
from django.contrib.auth.backends import ModelBackend
from django.contrib.auth import get_user_model
from django.conf import settings
###################################
""" DEFAULT SETTINGS + ALIAS """
###################################
try:
am = settings.AUTHENTICATION_METHOD
except:
am = 'both'
try:
cs = settings.AUTHENTICATION_CASE_SENSITIVE
except:
cs = 'both'
#####################
""" EXCEPTIONS """
#####################
VALID_AM = ['username', 'email', 'both']
VALID_CS = ['username', 'email', 'both', 'none']
if (am not in VALID_AM):
raise Exception("Invalid value for AUTHENTICATION_METHOD in project "
"settings. Use 'username','email', or 'both'.")
if (cs not in VALID_CS):
raise Exception("Invalid value for AUTHENTICATION_CASE_SENSITIVE in project "
"settings. Use 'username','email', 'both' or 'none'.")
############################
""" OVERRIDDEN METHODS """
############################
class DualAuthentication(ModelBackend):
"""
This is a ModelBacked that allows authentication
with either a username or an email address.
"""
def authenticate(self, username=None, password=None):
UserModel = get_user_model()
try:
if ((am == 'email') or (am == 'both')):
if ((cs == 'email') or cs == 'both'):
kwargs = {'email': username}
else:
kwargs = {'email__iexact': username}
user = UserModel.objects.get(**kwargs)
else:
raise
except:
if ((am == 'username') or (am == 'both')):
if ((cs == 'username') or cs == 'both'):
kwargs = {'username': username}
else:
kwargs = {'username__iexact': username}
user = UserModel.objects.get(**kwargs)
finally:
try:
if user.check_password(password):
return user
except:
# Run the default password hasher once to reduce the timing
# difference between an existing and a non-existing user.
UserModel().set_password(password)
return None
def get_user(self, username):
UserModel = get_user_model()
try:
return UserModel.objects.get(pk=username)
except UserModel.DoesNotExist:
return None
答案 6 :(得分:1)
最新版本的django-registration允许一些不错的自定义并可能完成这项工作 - 文档https://bitbucket.org/ubernostrum/django-registration/src/fad7080fe769/docs/backend-api.rst
答案 7 :(得分:1)
if user_form.is_valid():
# Save the user's form data to a user object without committing.
user = user_form.save(commit=False)
user.set_password(user.password)
#Set username of user as the email
user.username = user.email
#commit
user.save()
完美地工作......对于django 1.11.4
答案 8 :(得分:0)
您还可以在以下链接中找到关于此主题的有趣讨论:
答案 9 :(得分:0)
最简单的方法是根据登录视图中的电子邮件查找用户名。这样你就可以把其他一切都留下来了:
from django.contrib.auth import authenticate, login as auth_login
def _is_valid_email(email):
from django.core.validators import validate_email
from django.core.exceptions import ValidationError
try:
validate_email(email)
return True
except ValidationError:
return False
def login(request):
next = request.GET.get('next', '/')
if request.method == 'POST':
username = request.POST['username'].lower() # case insensitivity
password = request.POST['password']
if _is_valid_email(username):
try:
username = User.objects.filter(email=username).values_list('username', flat=True)
except User.DoesNotExist:
username = None
kwargs = {'username': username, 'password': password}
user = authenticate(**kwargs)
if user is not None:
if user.is_active:
auth_login(request, user)
return redirect(next or '/')
else:
messages.info(request, "<stvrong>Error</strong> User account has not been activated..")
else:
messages.info(request, "<strong>Error</strong> Username or password was incorrect.")
return render_to_response('accounts/login.html', {}, context_instance=RequestContext(request))
在您的模板中相应地设置下一个变量,即
<form method="post" class="form-login" action="{% url 'login' %}?next={{ request.GET.next }}" accept-charset="UTF-8">
并输入您的用户名/密码输入正确的名称,即用户名,密码。
更新:
或者,if _is_valid_email(email):call可以替换为if&#39; @&#39;用户名。这样你可以删除_is_valid_email函数。这实际上取决于您如何定义用户名。如果你允许&#39; @&#39;它将无效。用户名中的字符。
答案 10 :(得分:0)
我认为最快的方法是创建一个继承自UserCreateForm
的表单,然后使用username
覆盖forms.EmailField
字段。然后,对于每个新的注册用户,他们需要使用他们的电子邮件地址登录。
例如:
<强> urls.py 强>
...
urlpatterns += url(r'^signon/$', SignonView.as_view(), name="signon")
<强> views.py 强>
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from django import forms
class UserSignonForm(UserCreationForm):
username = forms.EmailField()
class SignonView(CreateView):
template_name = "registration/signon.html"
model = User
form_class = UserSignonForm
<强> signon.html 强>
...
<form action="#" method="post">
...
<input type="email" name="username" />
...
</form>
...
答案 11 :(得分:0)
不确定人们是否正在努力实现这一目标,但我发现很好(干净)的方式只是要求发送电子邮件,然后在保存之前将用户名设置为视图中的电子邮件。
我的UserForm只需要电子邮件和密码:
class UserForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput())
class Meta:
model = User
fields = ('email', 'password')
然后在我看来,我添加了以下逻辑:
if user_form.is_valid():
# Save the user's form data to a user object without committing.
user = user_form.save(commit=False)
user.set_password(user.password)
#Set username of user as the email
user.username = user.email
#commit
user.save()