使用django自带的user做外键的方法


Posted in Python onNovember 30, 2020

一、使用django自带的user做外键,可以直接在model中使用。只需导入settings模块

使用方法:
在app应用(此处是Product应用)中的models.py文件,导入settings模块

# Product / models.py
from django.db import models
from django.contrib.auth import settings


class Product(models.Model):
  productName = models.CharField('产品名称', max_length=20)
  productDescription = models.CharField('产品描述', max_length=100)
  producer = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name='负责人',             on_delete=models.SET_NULL,blank=True, null=True)
  createTime = models.DateTimeField('创建时间', auto_now=True)

  class Meta:
    verbose_name = '产品管理'
    verbose_name_plural = '产品管理'

  def __str__(self):
    return self.productName

使用django自带的user做外键的方法

二、自定义User Model

方法一、扩展AbstractUser类:只增加字段

app/models.py

from django.contrib.auth.models import AbstractUser
from django.db import models

class NewUser(AbstractUser):
	new_field = models.CharField(max_length=100)

同时,需要在global_settings文件中设置:

AUTH_USER_MODEL = "app.NewUser"

方法二、扩展AbstractBaseUser类
AbstractBaseUser中只包含3个field: password, last_login和is_active. 扩展方式同上

# django.contrib.auth.base_user
class AbstractBaseUser(models.Model):
  password = models.CharField(_('password'), max_length=128)
  last_login = models.DateTimeField(_('last login'), blank=True, null=True)

  is_active = True

  REQUIRED_FIELDS = []

  # Stores the raw password if set_password() is called so that it can
  # be passed to password_changed() after the model is saved.
  _password = None

  class Meta:
    abstract = True

  def __str__(self):
    return self.get_username()

  def save(self, *args, **kwargs):
    super().save(*args, **kwargs)
    if self._password is not None:
      password_validation.password_changed(self._password, self)
      self._password = None

  def get_username(self):
    """Return the username for this User."""
    return getattr(self, self.USERNAME_FIELD)

  def clean(self):
    setattr(self, self.USERNAME_FIELD, self.normalize_username(self.get_username()))

  def natural_key(self):
    return (self.get_username(),)

  @property
  def is_anonymous(self):
    """
    Always return False. This is a way of comparing User objects to
    anonymous users.
    """
    return False

  @property
  def is_authenticated(self):
    """
    Always return True. This is a way to tell if the user has been
    authenticated in templates.
    """
    return True

  def set_password(self, raw_password):
    self.password = make_password(raw_password)
    self._password = raw_password

  def check_password(self, raw_password):
    """
    Return a boolean of whether the raw_password was correct. Handles
    hashing formats behind the scenes.
    """
    def setter(raw_password):
      self.set_password(raw_password)
      # Password hash upgrades shouldn't be considered password changes.
      self._password = None
      self.save(update_fields=["password"])
    return check_password(raw_password, self.password, setter)

  def set_unusable_password(self):
    # Set a value that will never be a valid hash
    self.password = make_password(None)

  def has_usable_password(self):
    """
    Return False if set_unusable_password() has been called for this user.
    """
    return is_password_usable(self.password)

  def get_session_auth_hash(self):
    """
    Return an HMAC of the password field.
    """
    key_salt = "django.contrib.auth.models.AbstractBaseUser.get_session_auth_hash"
    return salted_hmac(key_salt, self.password).hexdigest()

  @classmethod
  def get_email_field_name(cls):
    try:
      return cls.EMAIL_FIELD
    except AttributeError:
      return 'email'

  @classmethod
  def normalize_username(cls, username):
    return unicodedata.normalize('NFKC', username) if isinstance(username, str) else username

到此这篇关于使用django自带的user做外键的方法的文章就介绍到这了,更多相关django user做外键内容请搜索三水点靠木以前的文章或继续浏览下面的相关文章希望大家以后多多支持三水点靠木!

Python 相关文章推荐
Python使用OpenCV进行标定
May 08 Python
Python简单获取网卡名称及其IP地址的方法【基于psutil模块】
May 24 Python
使用python根据端口号关闭进程的方法
Nov 06 Python
解决python xlrd无法读取excel文件的问题
Dec 25 Python
用scikit-learn和pandas学习线性回归的方法
Jun 21 Python
django 捕获异常和日志系统过程详解
Jul 18 Python
djano一对一、多对多、分页实例代码
Aug 16 Python
jupyter 中文乱码设置编码格式 避免控制台输出的解决
Apr 20 Python
基于Tensorflow的MNIST手写数字识别分类
Jun 17 Python
Python Switch Case三种实现方法代码实例
Jun 18 Python
Python机器学习工具scikit-learn的使用笔记
Jan 28 Python
Python学习开发之图形用户界面详解
Aug 23 Python
python 实现简易的记事本
Nov 30 #Python
详解pycharm自动import所需的库的操作方法
Nov 30 #Python
Django REST Framework 分页(Pagination)详解
Nov 30 #Python
python代码实现猜拳小游戏
Nov 30 #Python
Django 权限管理(permissions)与用户组(group)详解
Nov 30 #Python
python 如何引入协程和原理分析
Nov 30 #Python
Django缓存Cache使用详解
Nov 30 #Python
You might like
php与paypal整合方法
2010/11/28 PHP
php float不四舍五入截取浮点型字符串方法总结
2013/10/28 PHP
php字符编码转换之gb2312转为utf8
2013/10/28 PHP
kindeditor 加入七牛云上传的实例讲解
2017/11/12 PHP
用PHP做了一个领取优惠券活动的示例代码
2019/07/05 PHP
网页中可关闭的漂浮窗口实现可自行调节
2013/08/20 Javascript
Javascript表单验证要注意的事项
2014/09/29 Javascript
js字符串完全替换函数分享
2014/12/03 Javascript
JavaScript使用RegExp进行正则匹配的方法
2015/07/11 Javascript
微信小程序中用WebStorm使用LESS
2017/03/08 Javascript
JS验证input输入框(字母,数字,符号,中文)
2017/03/23 Javascript
MvcPager分页控件 适用于Bootstrap
2017/06/03 Javascript
vue-awesome-swiper 基于vue实现h5滑动翻页效果【推荐】
2018/11/08 Javascript
微信JS-SDK updateAppMessageShareData安卓不能自定义分享详解
2019/03/29 Javascript
安装多版本Vue-CLI的实现方法
2020/03/24 Javascript
vue的hash值原理也是table切换实例代码
2020/12/14 Vue.js
[01:18:36]LGD vs VP Supermajor 败者组决赛 BO3 第一场 6.10
2018/07/04 DOTA
Python文件和目录操作详解
2015/02/08 Python
python实现的jpg格式图片修复代码
2015/04/21 Python
Python中设置变量访问权限的方法
2015/04/27 Python
使用Python操作excel文件的实例代码
2017/10/15 Python
python实现用户答题功能
2018/01/17 Python
django ajax json的实例代码
2018/05/29 Python
PyQt 实现使窗口中的元素跟随窗口大小的变化而变化
2019/06/18 Python
python 爬虫百度地图的信息界面的实现方法
2019/10/27 Python
如何查看Django ORM执行的SQL语句的实现
2020/04/20 Python
keras得到每层的系数方式
2020/06/15 Python
Python2及Python3如何实现兼容切换
2020/09/01 Python
韩国保养品、日本药妆购物网:小三美日
2018/12/30 全球购物
CK巴西官方网站:Calvin Klein巴西
2019/07/19 全球购物
自我评价怎么写好呢?
2013/12/05 职场文书
医学实习生自我鉴定
2013/12/12 职场文书
优秀志愿者事迹材料
2014/02/03 职场文书
2015世界地球日活动总结
2015/02/09 职场文书
我们的节日中秋节活动总结
2015/03/23 职场文书
2015教师个人年度工作总结
2015/10/23 职场文书