使用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网络编程之读取网站根目录实例
Sep 30 Python
Python版微信红包分配算法
May 04 Python
Python socket编程实例详解
May 27 Python
Python使用Beautiful Soup包编写爬虫时的一些关键点
Jan 20 Python
python 3.7.0 下pillow安装方法
Aug 27 Python
Win10下python 2.7.13 安装配置方法图文教程
Sep 18 Python
Python基础之字符串常见操作经典实例详解
Feb 26 Python
解决windows下python3使用multiprocessing.Pool出现的问题
Apr 08 Python
python实现计算器简易版
Dec 17 Python
如何通过安装HomeBrew来安装Python3
Dec 23 Python
Python Django 后台管理之后台模型属性详解
Apr 25 Python
拒绝盗图!教你怎么用python给图片加水印
Jun 04 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
超神学院:鹤熙已踏入神圣领域,实力不比凯莎弱
2020/03/02 国漫
php中iconv函数使用方法
2008/05/24 PHP
ThinkPHP3.2框架使用addAll()批量插入数据的方法
2017/03/16 PHP
JS中彻底删除JSON对象组成的数组中的元素
2020/09/22 PHP
js 单击式的下拉菜单效果实例
2013/08/13 Javascript
CheckBoxList多选样式jquery、C#获取选择项
2013/09/06 Javascript
javascript动态修改Li节点值的方法
2015/01/20 Javascript
js判断一个字符串是否包含一个子串的方法
2015/01/26 Javascript
jQuery下拉美化搜索表单效果代码分享
2015/08/25 Javascript
Nodejs从有门道无门菜鸟起飞必看教程
2016/07/20 NodeJs
JS动态生成年份和月份实例代码
2017/02/04 Javascript
js单页hash路由原理与应用实战详解
2017/08/14 Javascript
解决Linux无法正常安装与卸载Node.js的方法
2018/01/19 Javascript
vue axios 在页面切换时中断请求方法 ajax
2018/03/05 Javascript
JavaScript实现多球运动效果
2020/09/07 Javascript
Python写的Tkinter程序屏幕居中方法
2015/03/10 Python
Python实现LRU算法的2种方法
2015/06/24 Python
Python入门之三角函数sin()函数实例详解
2017/11/08 Python
python实现Floyd算法
2018/01/03 Python
详解pandas如何去掉、过滤数据集中的某些值或者某些行?
2019/05/15 Python
python全栈知识点总结
2019/07/01 Python
python 基于selectors库实现文件上传与下载
2020/12/31 Python
HTML5拖拽文件到浏览器并实现文件上传下载功能代码
2013/06/06 HTML / CSS
html5借用repeating-linear-gradient实现一把刻度尺(ruler)
2019/09/09 HTML / CSS
日本一家专门经营各种箱包的大型网站:Traveler Store
2016/08/03 全球购物
Ellos丹麦:时尚和服装在线
2016/09/19 全球购物
Christys’ Hats官网:英国帽子制造商
2018/11/28 全球购物
英国性能汽车零件和发动机配件在线:Maxpeedingrods
2019/11/05 全球购物
大学生实习思想汇报
2014/01/12 职场文书
家长评语大全
2014/01/22 职场文书
致200米运动员广播稿
2014/02/06 职场文书
高三毕业寄语
2014/04/10 职场文书
小学二年级数学教学计划
2015/01/20 职场文书
学术研讨会主持词
2015/07/04 职场文书
如何制定一份可行的计划!
2019/06/21 职场文书
python 爬取华为应用市场评论
2021/05/29 Python