我有如下的扩展用户模型..
class User(AbstractEmailUser):
first_name = models.CharField(verbose_name=_('First name'),max_length=128)
last_name = models.CharField(verbose_name=_('Last name'), max_length=128)
avatar = StdImageField(upload_to='user_avatars/', null=True, blank=True, variations={
'thumbnail': (settings.AVATAR_THUMBNAIL_WIDTH, settings.AVATAR_THUMBNAIL_HEIGHT, True)
})
user_name = models.CharField(null=True,blank=True,verbose_name=_('User id'), max_length=128)
def get_short_name(self):
return self.last_name
def get_full_name(self):
return "%s %s" % (self.first_name, self.last_name)
def __unicode__(self):
return self.email
def get_thumbnail_url(self):
return self.avatar.thumbnail.url if self.avatar else None
我想在扩展用户模型中使用电子邮件字段和admin by user_name字段验证除admin之外的所有用户.....我正在使用django 1.9
有没有默认方法可以做到这一点......
答案 0 :(得分:1)
因此,您应该创建自定义身份验证后端。身份验证之前的用户是匿名的,因此我们无法判断他是否是管理员。我认为你可以这样做的方法是使用用户名或电子邮件验证用户,如果他们是管理员用户验证他们使用的任何东西(用户名或电子邮件),但普通用户应该使用电子邮件,如果不是,则返回None。
WebClient cl = new WebClient();
NameValueCollection nvm = new NameValueCollection();
nvm["name"] = data.Name;
nvm["description"] = data.Description;
nvm["file"] = // File.OpenRead(data.FilePath) ? or how send file content ?
cl.UploadValues("https://database.org/upload.php", "POST", nvm);
和from django.contrib.auth.backends import ModelBackend
from django.contrib.auth import get_user_model
from django.core.validators import validate_email
from django.contrib.auth.hashers import check_password
class MyAuthenticationBackend(ModelBackend):
"""
Authenticate All users if Email is used but just the admin if username is used
"""
def authenticate(self, request, username=None, password=None):
try:
validate_email(username)
valid_email = True
kwargs = {'email': username}
except:
valid_email = False
kwargs = {'username': username}
try:
user = get_user_model().objects.get(**kwargs)
except get_user_model().DoesNotExist:
print("User model does not exist!")
return None
if valid_email and user.check_password(password):
print("Email used. Authenticate all users")
return user
elif not valid_email and user.check_password(password) and user.is_admin:
print("Username used. Authenticate admin users")
return user
else:
print("something else return None")
return None
def get_user(self, user_id):
try:
return get_user_model().objects.get(pk=user_id)
except get_user_model().DoesNotExist:
return None
档案
settings.py
用于身份验证的字段应该具有唯一设置为True,而空白和null应该为False。
AUTHENTICATION_BACKENDS = [
'app.admin.MyAuthenticationBackend',
]