Welcome 微信登录
编程资源 图片资源库 蚂蚁家优选 PDF转换器

首页 / 操作系统 / Linux / Django1.5自定义User模型

Django1.5自定义用户profile可谓简单很多,编写自己的model类MyUser,MyUser至少要满足如下要求:
  1. 必须有一个整型的主键
  2. 有一个唯一性约束字段,比如username或者email,用来做用户认证
  3. 提供一种方法以“short”和“long"的形式显示user,换种说法就是要实现 getfullname和getshortname方法。
一:在project中创建一个account appdjango-admin startapp account二:自定义MyUser实现自定义User模型最简单的方式就是继承AbstractBaseUser,AbstractBaseUser实现了User的核心功能,你只需对一些额外的细节进行实现就可以了。可以看看AbstractBaseUser的源码:@python_2_unicode_compatibleclass AbstractBaseUser(models.Model):password = models.CharField(_("password"), max_length=128)last_login = models.DateTimeField(_("last login"), default=timezone.now)is_active = TrueREQUIRED_FIELDS = []class Meta:abstract = Truedef get_username(self):"Return the identifying username for this User"return getattr(self, self.USERNAME_FIELD)def __str__(self):return self.get_username()def natural_key(self):return (self.get_username(),)def is_anonymous(self):"""Always returns False. This is a way of comparing User objects toanonymous users."""return Falsedef is_authenticated(self):"""Always return True. This is a way to tell if the user has beenauthenticated in templates."""return Truedef set_password(self, raw_password):self.password = make_password(raw_password)def check_password(self, raw_password):"""Returns a boolean of whether the raw_password was correct. Handleshashing formats behind the scenes."""def setter(raw_password):self.set_password(raw_password)self.save(update_fields=["password"])return check_password(raw_password, self.password, setter)def set_unusable_password(self):# Sets a value that will never be a valid hashself.password = make_password(None)def has_usable_password(self):return is_password_usable(self.password)def get_full_name(self):raise NotImplementedError()def get_short_name(self):raise NotImplementedError()AbstractBaseUser只有getfullname和getshortname方法没有实现了。 接下来我们就通过继承AbstractBaseUser来自定义User模型叫MyUser:class MyUser(AbstractBaseUser, PermissionsMixin):username = models.CharField("username", max_length=30, unique=True,db_index=True)email = models.EmailField("email address",max_length=254, unique=True)date_of_birth = models.DateField("date of birth", blank=True, null=True)USERNAME_FIELD = "email"REQUIRED_FIELDS = ["username"]is_staff = models.BooleanField("staff status", default=False,help_text="Designates whether the user can log into this admin ""site.")is_active = models.BooleanField("active", default=True,help_text="Designates whether this user should be treated as " "active. Unselect this instead of deleting accounts.")def get_full_name(self):full_name = "%s %s" % (self.first_name, self.last_name)return full_name.strip()def get_short_name(self):return self.first_nameobjects = MyUserManager()USERNAME_FIELD :作为用户登录认证用的字段,可以usename,或者email等,但必须是唯一的。REQUIRED_FIELDS :使用createsuperuser命令创建超级用户时提示操作者输入的字段is_staff :判断用户是否可以登录管理后台is_active :判断用户是否可以正常登录三:自定义MyUserManager同时要为MyUser自定义个一个manager,通过继承BaseUserManager,提供creat_user和create_superuser方法。class MyUserManager(BaseUserManager):def create_user(self, username, email=None, password=None, **extra_fields):now = timezone.now()if not email:raise ValueError("The given email must be set")email = UserManager.normalize_email(email)user = self.model(username=username, email=email, is_staff=False, is_active=True, is_superuser=False, last_login=now, **extra_fields)user.set_password(password)user.save(using=self._db)return userdef create_superuser(self, username, email, password, **extra_fields):u = self.create_user(username, email, password, **extra_fields)u.is_staff = Trueu.is_active = Trueu.is_superuser = Trueu.save(using=self._db)return u四:指定AUTHUSERMODEL覆盖默认的AUTHUSERMODEL,在settings.py文件中增加: AUTHUSERMODEL = "user.MyUser"五:注册MyUser在account模块下创建admin.py,添加如下代码把MyUser模型注册到admin中:from django.contrib import adminfrom user.models import MyUseradmin.site.register(MyUser)总结:实现自定义的User模型在Django1.5足够简单方便,根据自己需求继承AbstractBaseUser就可以了。当然如果你想了解更多关于Django 自定义用户模型相关内容,官方文档告诉你更多更好的完好如果你有什么建议和问题欢迎留言。Django1.8返回json字符串和接收post的json字符串内容  http://www.linuxidc.com/Linux/2015-07/120226.htm如何使用 Docker 组件开发 Django 项目?  http://www.linuxidc.com/Linux/2015-07/119961.htmUbuntu Server 12.04 安装Nginx+uWSGI+Django环境 http://www.linuxidc.com/Linux/2012-05/60639.htm Django+Nginx+uWSGI 部署 http://www.linuxidc.com/Linux/2013-02/79862.htm Django实战教程 http://www.linuxidc.com/Linux/2013-09/90277.htm Django Python MySQL Linux 开发环境搭建 http://www.linuxidc.com/Linux/2013-09/90638.htm Django 的详细介绍:请点这里
Django 的下载地址:请点这里本文永久更新链接地址:http://www.linuxidc.com/Linux/2015-08/121374.htm