django用户注册、登录、注销和用户扩展的示例

yizhihongxing

让我来详细讲解一下关于“Django用户注册、登录、注销和用户扩展的示例”的攻略。

概述

在Django中,用户认证是开箱即用的,也就是说你可以方便地创建用户账户、实现登录认证等操作。本攻略将介绍基本的Django用户认证流程,以及如何通过扩展用户模型的方法增加字段来完成用户注册和登录的过程。

本文涉及到的环境以及版本信息如下:

  • Python 3.7.9
  • Django 3.1.2

示例一:用户注册和登录

1. 创建Django项目和应用

首先通过Django提供的命令创建项目和应用:

$ django-admin startproject mysite
$ cd mysite
$ python manage.py startapp accounts

其中,mysite是项目名称,accounts是应用名称。

2. 设置数据库

在Django中,我们需要先设置数据库。在mysite/settings.py文件中,找到DATABASES字段,并按照自己的需求进行设置。

# mysite/settings.py

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}

上述配置使用SQLite作为数据库,并将数据库文件保存在项目根目录下的db.sqlite3文件中。

3. 创建用户模型

在Django中,用户模型已经被封装成了django.contrib.auth.models.User模型。但如果仅仅是使用这个默认的用户模型,可能会存在一些限制。因此,我们通常需要对用户模型进行扩展。

以下是示例中的用户模型:

# accounts/models.py

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

class User(AbstractUser):
    nickname = models.CharField(max_length=50, blank=True)
    avatar = models.ImageField(upload_to='avatars', null=True, blank=True)

在这个扩展后的用户模型中,我们添加了两个字段,分别是用户昵称和用户头像。

4. 配置Django认证系统

在Django中,系统默认使用django.contrib.auth中的认证系统。我们需要在mysite/settings.py文件中设置一些参数来启用认证系统。

# mysite/settings.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'accounts',  # 加入此应用
]

# 设置认证后端为django.contrib.auth.backends.ModelBackend
AUTHENTICATION_BACKENDS = [
    'django.contrib.auth.backends.ModelBackend',
]

# 设置用户模型为accounts.models.User
AUTH_USER_MODEL = 'accounts.User'

其中,AUTHENTICATION_BACKENDS用于设置认证后端,AUTH_USER_MODEL用于指定用户模型。

5. 创建用户注册和登录视图

接下来,我们需要创建用户注册与登录的视图,并编写相应的html模板。以下是示例中的代码:

# accounts/views.py

from django.shortcuts import render, redirect
from django.contrib.auth import login, authenticate
from django.contrib.auth.forms import AuthenticationForm
from .forms import UserCreationForm

def register(request):
    if request.method == 'POST':
        form = UserCreationForm(request.POST, request.FILES)
        if form.is_valid():
            new_user = form.save(commit=False)
            new_user.set_password(form.cleaned_data['password1'])
            new_user.save()
            return redirect('login')
    else:
        form = UserCreationForm()
    return render(request, 'accounts/register.html', {'form': form})

def user_login(request):
    if request.method == 'POST':
        form = AuthenticationForm(data=request.POST)
        if form.is_valid():
            user = authenticate(username=form.cleaned_data['username'],
                                password=form.cleaned_data['password'])
            if user is not None:
                login(request, user)
                return redirect('/')
    else:
        form = AuthenticationForm()
    return render(request, 'accounts/login.html', {'form': form})
<!-- accounts/templates/accounts/register.html -->

{% extends 'base.html' %}

{% block content %}
  <h2>注册</h2>
  <form method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit">注册</button>
  </form>
{% endblock %}
<!-- accounts/templates/accounts/login.html -->

{% extends 'base.html' %}

{% block content %}
  <h2>登录</h2>
  <form method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit">登录</button>
  </form>
{% endblock %}

在上面的代码中,accounts/forms.py定义了UserCreationForm表单,用于处理用户注册时的表单数据。accounts/templates/accounts/register.html是用户注册的html页面,以及登录页面的html表示。

6. URL配置

最后,我们需要在mysite/urls.py文件中配置视图对应的URL。

# mysite/urls.py

from django.contrib import admin
from django.urls import path, include
from django.conf.urls.static import static
from django.conf import settings
from accounts.views import register, user_login

urlpatterns = [
    path('admin/', admin.site.urls),
    path('accounts/login/', user_login, name='login'),
    path('accounts/register/', register, name='register'),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

现在,用户认证系统就配置完成了。在浏览器中访问http://127.0.0.1:8000/accounts/register/即可进行用户注册,访问http://127.0.0.1:8000/accounts/login/即可进行用户登录。

示例二:UserProfile扩展

1. 创建UserProfile模型

扩展Django用户模型的方法有很多,本示例中将使用OneToOneField模型来扩展用户模型,即在已有的用户模型基础上创建一个一对一的用户信息模型。

# accounts/models.py

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

class UserProfile(models.Model):
    user = models.OneToOneField(
        AbstractUser,
        on_delete=models.CASCADE,
        related_name='profile'
    )
    nickname = models.CharField(max_length=50, blank=True)
    avatar = models.ImageField(upload_to='avatars', null=True, blank=True)

    def __str__(self):
        return f'{self.user.username}的信息'

在这个示例中,我们新建一个UserProfile模型,并使用OneToOneField与User模型建立一对一的关系,用来存储额外的用户信息。

2. 创建UserProfile表单

accounts/forms.py 文件中,定义一个用于修改UserProfile表单的类。

# accounts/forms.py

from django import forms
from .models import UserProfile

class UserProfileForm(forms.ModelForm):
    class Meta:
        model = UserProfile
        fields = ['nickname', 'avatar']
        widgets = {
            'avatar': forms.FileInput(attrs={'class': 'custom-file-input'}),
        }

在这个表单中,我们将UserProfile模型中的nickname和avatar字段放在了表单中,并对头像文件添加了样式。

3. 创建UserProfile视图

accounts/views.py 文件中,定义 profile 视图,用于展示和更新用户的 UserProfile

# accounts/views.py

from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from .models import UserProfile
from .forms import UserProfileForm

@login_required(login_url='/accounts/login/')
def profile(request):
    if request.method == 'POST':
        profile_form = UserProfileForm(request.POST, request.FILES,
                                        instance=request.user.profile)
        if profile_form.is_valid():
            profile_form.save()
            return redirect('profile')
    else:
        profile_form = UserProfileForm(instance=request.user.profile)
    return render(request, 'accounts/profile.html', {'profile_form': profile_form})

在这个视图中,我们使用 login_required 装饰器保证只有登录的用户才能访问个人信息的页面。在 POST 请求的情况下,我们通过读取 request.FILES 来处理上传文件,并将更新过的 UserProfileForm 保存到数据库。

4. 创建UserProfile的URL

mysite/urls.py 文件中加入如下一行代码:

# mysite/urls.py

urlpatterns = [
    # ...
    path('accounts/profile/', profile, name='profile'),
]

5. 创建UserProfile的模板

accounts/templates/accounts/ 目录下新建 profile.html,并编写如下代码:

{% extends 'base.html' %}

{% block content %}
  <h2>个人信息</h2>
  <p><a href="{% url 'logout' %}">退出</a></p>
  <form method="post" enctype="multipart/form-data">
    {% csrf_token %}
    {{ profile_form.as_p }}
    <div class="form-group">
      <button type="submit" class="btn btn-primary">保存</button>
    </div>
  </form>
{% endblock %}

在上面的代码中,我们通过 {% url 'logout' %} 将用户退出的链接与内建的 Django URL 匹配。

6. 配置media

由于上传的文件需要保存到服务器上,所以我们需要在 mysite/settings.py 上添加如下配置:

# mysite/settings.py

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')  # 指定文件存储路径
MEDIA_URL = '/media/'  # 指定在url中的前缀,如 /media/test.png

在项目根目录中新建一个 media/ 目录,所有上传的文件都将存放在这个目录中。

至此,我们已经完成了UserProfile的扩展,可以在浏览器中访问 http://127.0.0.1:8000/accounts/profile/ 来设置个人信息,同时也可以在我们的用户注册视图中添加更多的信息。

以上就是Django用户注册、登录、注销和用户扩展的示例攻略,希望对你有所帮助。

本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:django用户注册、登录、注销和用户扩展的示例 - Python技术站

(0)
上一篇 2023年5月16日
下一篇 2023年5月16日

相关文章

  • 对DJango视图(views)和模版(templates)的使用详解

    以下是关于“对Django视图(views)和模版(templates)的使用详解”的完整攻略: 1. 什么是Django视图(Views)和模版(Templates) Django视图(Views)是与请求(requests)相关联的Python函数或方法,它们接收HTTP请求并以HTTP响应形式返回。Django模版(Templates)则是用来渲染数据…

    Django 2023年5月16日
    00
  • Django项目的ORM操作之–模型类数据查询

    1.查询基本格式及理解: 类名.objects.[查询条件]   例如我们要查询数据库中一张表(bookinfo)的所有数据,sql语句为:select * from bookinfo,   对应模型类的操作是: BookInfo.objects.all()     cd到当前django项目的目录下,进入携带django环境的python解释器进行测试操作…

    Django 2023年4月13日
    00
  • 一文了解Django缓存机制

    一文了解Django缓存机制 缓存的概念 缓存是指存储一份计算过的结果,以便后续快速访问和获取数据的技术。相对于实时读取、计算等方式,缓存已被广泛应用在提高应用程序性能、减轻服务器压力等方面。 Django内置了缓存框架,支持多种缓存后端,包括内存缓存、文件缓存、Redis缓存等。 缓存使用步骤 1.启用缓存 在settings.py中配置CACHES,指明…

    Django 2023年5月16日
    00
  • vue+django配置

    1.写完Vue项目 修改src/router/index.js的Router对象 export default new Router({ mode: ‘history’, routes: [ { path: ‘/’, name: ‘Pos’, component: Pos } ] }) //添加mode:’history’ 2.修改config/index.…

    Django 2023年4月13日
    00
  • Python3创建django项目

    1,安装Python环境 2.在cmd命令行,用pip安装Djang。我用的Python3。所以pip3 install django 查看Django环境是否正常,引入包没有报错,说明环境正确: 3.在pycharm里创建Django项目   用命令行创建:     进入想要安置项目的目录,命令行输入:django-admin startproject m…

    2023年4月10日
    00
  • 在Window环境下,使用Django shell 命令查询数据库

    1 .首先需要配置python的环境变量 ,也就是python的安装路径 我的本地的路径是C:\Users\Administrator\AppData\Local\Programs\Python\Python37-32 然后打开cmd   输入python ,显示python的版本,表示配置成功,否则失败, 我这边默认python 和Django都是安装完成…

    Django 2023年4月11日
    00
  • Django框架文件保存的流程(以及自定义FDFS)

    Django框架文件保存的流程 自定义文件存储类过程说明 from django.core.files.storage import Storage from django.conf import settings from fdfs_client.client import Fdfs_client from rest_framework.exception…

    Django 2023年4月13日
    00
  • python–Django(后台管理模块)

    一、准备工作   1.创建应用 python manage.py startapp test   2.定义模型类     (1)打开刚创建的app目录test,打开models.py文件     (2)代码如下 from django.db import models class classes(models.Model): name = models.Ch…

    Django 2023年4月11日
    00
合作推广
合作推广
分享本页
返回顶部