---
title: "用户密码Django1.5内置的用户认证系统介绍（之二）使用User对象"
author: "wwweducn"
date: "2013-04-26T19:10:19Z"
tags: []
categories: ["编程语言"]
slug: "django1-5-user"
draft: false
lastmod: "2013-04-26T19:10:19Z"
id: 1855394
url: "https://wwweducn.iteye.com/blog/1855394"
---

本文朋友在深圳吃饭的时候突然想到的...今天就有想写几篇关于用户密码的博客，所以回家到后之就奋笔疾书的写出来发表了

    **说明**：网上有关Django用户系统的内容不少，但是似乎没有针对Django1.5的。可能是因为Django1.5前目用的人还多不吧。（python3.x貌似也是种这情况）。因为自己要用，所以顺手在学习官方文档的中程过，边看边译。基本忠于原文（&gt;95%），小分部太啰嗦的内容就当适意译、简化了。后续还会参加分部自己的会体（会注出），供参考。如有错讹、不精确处之，还请大家指教。

    Source：[https://docs.djangoproject.com/en/1.5/topics/auth/default/](https://docs.djangoproject.com/en/1.5/topics/auth/default/)

 

    

# 应用Django证认系统（authentication system）

    本文分析Django UAS在缺省置配下的基本功能用法。它几乎可以足满大分部的目项相干需求。对那些基本功能没法足满的目项，Django还支撑证认与权授功能的扩展和定制化（[*extension and customization*](https://docs.djangoproject.com/en/1.5/topics/auth/customizing/)）

    Again，Django UAS包含了证认和权授，因为这两分部的功能互相联关，所以只用UAS/证认系统（authentication system）来指示这两分部。

    

## 用户象对 User objects[¶](https://docs.djangoproject.com/en/1.5/topics/auth/default/#user-objects "Permalink to this headline")

    用户象对是证认系统的心核。用户象对平日用来代表网站的用户，并支撑例如访问控制、注册用户、联关建创者和内容等。在Django证认框架中只有一个用户类，例如超级用户（ ‘superusers’）或人员（‘staff’）用户只不过是雷同用户象对设置了不同属性而已。

    缺省用户的基本属性包含：

    

- 用户名username
- 密码password
- email
- 名字first name
- 姓氏last name

    拜见整完的API文档（[full API documentation](https://docs.djangoproject.com/en/1.5/ref/contrib/auth/#django.contrib.auth.models.User "django.contrib.auth.models.User")），本文档的以下分部是面向任务方法编排的。

    

### 建创用户 Creating users

    建创用户最直接的方法是应用内置的 [create\_user()](https://docs.djangoproject.com/en/1.5/ref/contrib/auth/#django.contrib.auth.models.UserManager.create_user "django.contrib.auth.models.UserManager.create_user") 方法：

```
>>> from django.contrib.auth.models import User
>>> user = User.objects.create_user('john', 'lennon@thebeatles.com', 'johnpassword')
 
# At this point, user is a User object that has already been saved
# to the database. You can continue to change its attributes
# if you want to change other fields.
>>> user.last_name = 'Lennon'
>>> user.save()
```

如果你设置好了Django admin后台，你还可以应用Web后台来建创用户（[*create users interactively*](https://docs.djangoproject.com/en/1.5/topics/auth/default/#auth-admin)）。

### 建创超级用户 Creating superusers

    如果你已经在置配文件的 [INSTALLED\_APPS](https://docs.djangoproject.com/en/1.5/ref/settings/#std:setting-INSTALLED_APPS)里置配了'django.contrib.auth' ，那么在你第一次行运[manage.py syncdb](https://docs.djangoproject.com/en/1.5/ref/django-admin/#django-admin-syncdb) 时，会示提你建创一个超级用户。如果你在后之还想建创超级用户，你可以应用如下的命令行：

```
manage.py createsuperuser --username=joe --email=joe@example.com
```

序程会醒提你设置一个密码，如果输入了密码，用户就会被即立建创。如果你没有应用 [--username](https://docs.djangoproject.com/en/1.5/ref/django-admin/#django-admin-option---username) 或 [--email](https://docs.djangoproject.com/en/1.5/ref/django-admin/#django-admin-option---email) 项选，那么还会示提你输入这些内容。

### 变动密码 Changing passwords

    每日一道理  
最为值得珍惜的是今天，因为最容易流逝的就是今天，把握今天就是把握希望，分分秒秒只是瞬间，而所乘载的分分秒秒就叫做一天，时间的流逝往往是在不经意之间，人生几回，青春更珍贵，对于我们这个年龄的青少年来说，青春已不足二十载，在学习的生活中我们必须靠自己的力量，驾驭着自己的小船驶向希望的彼岸。

    Django不在用户模型（数据库表）中保存密码文本 (clear text)，而只保存哈希值 （体具拜见[*documentation of how passwords are managed*](https://docs.djangoproject.com/en/1.5/topics/auth/passwords/)）。因此，不要去直接作操用户的password属性。这也是为什么要供提helper函数来建创用户的原因。

    可以由多个方法来变动用户密码：

    [manage.py changepassword \*username\*](https://docs.djangoproject.com/en/1.5/ref/django-admin/#django-admin-changepassword) 供提了一个变动密码的命令行方法。它会示提输入新密码并认确输入，如果两次输入分歧，新密码会即立失效。如果你未指定用户，序程会试尝指定修改以后系统用户的密码。

    你也可以用序程来变动密码，方法是 [set\_password()](https://docs.djangoproject.com/en/1.5/ref/contrib/auth/#django.contrib.auth.models.User.set_password "django.contrib.auth.models.User.set_password")：

```
>>> from django.contrib.auth.models import User
>>> u = User.objects.get(username__exact='john')
>>> u.set_password('new password')
>>> u.save()
```

如果你置配好了Django admin后台，你也可以应用Web后台来修改用户密码（[*authentication system’s admin pages*](https://docs.djangoproject.com/en/1.5/topics/auth/default/#auth-admin)）

Django供提了相干的 [*views*](https://docs.djangoproject.com/en/1.5/topics/auth/default/#built-in-auth-views) 和 [*forms*](https://docs.djangoproject.com/en/1.5/topics/auth/default/#built-in-auth-forms) 可供用户应用修改密码。

    

### 用户证认Authenticating Users

    `authenticate`**(*\*\*credentials*)**

    要需证验username 和password时，应用 [authenticate()](https://docs.djangoproject.com/en/1.5/topics/auth/default/#django.contrib.auth.authenticate "django.contrib.auth.authenticate")方法。它受接表单参数供提的全安凭证（credentials）做参数，在缺省置配下，是 username 和password，如果证验通过就返回一个User象对，如果密码无效，则返回None：

```
from django.contrib.auth import authenticate
user = authenticate(username='john', password='secret')
if user is not None:
    # the password verified for the user
    if user.is_active:
        print("User is valid, active and authenticated")
    else:
        print("The password is valid, but the account has been disabled!")
else:
    # the authentication system was unable to verify the username and password
    print("The username and password were incorrect.")
```

 

文章结束给大家分享下程序员的一些笑话语录： 系统程序员  
　　1、头皮经常发麻，在看见一个蓝色屏幕的时候比较明显，在屏幕上什幺都看不见的时候尤其明显；  
　　2、乘电梯的时候总担心死机，并且在墙上找reset键；  
　　3、指甲特别长，因为按F7到F12比较省力；  
　　4、只要手里有东西，就不停地按，以为是Alt-F、S；  
　　5、机箱从来不上盖子，以便判断硬盘是否在转；  
　　6、经常莫名其妙地跟踪别人，手里不停按F10；  
　　7、所有的接口都插上了硬盘，因此觉得26个字母不够；  
　　8、一有空就念叨“下辈子不做程序员了”；  
　　9、总是觉得9号以后是a号；  
　　10、不怕病毒，但是很害怕自己的程序；