前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Django中拓展用户模型

Django中拓展用户模型

作者头像
Hsinyan
发布2022-06-19 18:00:10
9060
发布2022-06-19 18:00:10
举报

本文基于上一篇文章的基础上进行修改Django中allauth的安装与基本使用

拓展用户模型(UserProfile)

在这个部分,将开发两个功能,一个是用户登录后跳转到profile的界面(accounts/profile),另一个是允许登录用户修改个人信息(accounts/profile/update)。

第一步先创建UserProfile应用,用于存放用户的额外信息。

代码语言:javascript
复制
python manage.py startapp UserProfile

注册完应用后要要记得做一下几件事,一是在settings.py的INSTALLED_APPS中将应用进行注册,二是在项目的urls.py中注册url。

代码语言:javascript
复制
# settings.py
INSTALLED_APPS = [
    ......
    'UserProfile',
    ......
]
代码语言:javascript
复制
# urls.py

urlpatterns = [
    path('admin/', admin.site.urls),
    # 注册allauth
    path('accounts/', include('allauth.urls')),
    # 注册拓展的用户模型
    path('accounts/',include('UserProfile.urls'))
]

因为我们希望用户登录成功后跳转到profile界面,所以我们在setting.py中加入这句。

代码语言:javascript
复制
# accounts
LOGIN_REDIRECT_URL = '/accounts/profile/'

第二步,我们来定义拓展信息表。

由于Django自带的User模型字段邮箱,所以我们需要对其扩展,最便捷的方式就是创建UserProfile的模型,添加我们需要的字段。

定义UserProfile/models.py

代码语言:javascript
复制
from django.db import models
# 导入django自带的用户表作为外键
from django.contrib.auth.models import User
# Create your models here.

CAMPUS_TYPE = (
    ('江湾', '江湾'),
    ('仙溪', '仙溪'),
    ('河滨', '河滨'),
)

class UserProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile')
    name = models.CharField(max_length=50, null=True, blank=True, verbose_name='姓名')
    classes = models.CharField(max_length=50, blank=True, verbose_name='所在班级')
    bank_card = models.CharField(max_length=50,blank=True,verbose_name='中行卡号')
    identity_card = models.CharField(smax_length=18, blank=True, unique=True, verbose_name='身份证号码')
    telephone = models.CharField(max_length=50, blank=True, verbose_name='联系方式')
    campus = models.CharField(choices=CAMPUS_TYPE, max_length=50,blank=True, verbose_name='校区')
    modified_date = models.DateTimeField(auto_now=True, verbose_name='最后修改时间')

    class Meta:
        verbose_name = 'User Profile'

    def __str__(self):
        return "{}".format(self.user.__str__())

编写两个url对应两个视图,首先编写UserProfile内的urls.py

代码语言:javascript
复制
from django.urls import re_path,path
from UserProfile import views

app_name = "UserProfile"
urlpatterns = [
    re_path(r'^profile/$', views.profile, name='profile'),
    re_path(r'^profile/update/$', views.profile_update, name='profile_update'),
]

两个对应的视图函数

代码语言:javascript
复制
from django.shortcuts import render, get_object_or_404
from .models import UserProfile
from .forms import ProfileForm
from django.http import HttpResponseRedirect
from django.urls import reverse
from django.contrib.auth.decorators import login_required


@login_required
def profile(request):
    user = request.user
    return render(request, 'account/profile.html', {'user': user})


@login_required
def profile_update(request):
    user = request.user
    user_profile = get_object_or_404(UserProfile, user=user)

    if request.method == "POST":
        form = ProfileForm(request.POST)

        if form.is_valid():
            # 使用django自带User中first_name字段存放姓名
            user.first_name = form.cleaned_data['name']
            user.save()

            user_profile.name = form.cleaned_data['name']
            user_profile.classes = form.cleaned_data['classes']
            user_profile.bank_card = form.cleaned_data['bank_card']
            user_profile.identity_card = form.cleaned_data['identity_card']
            user_profile.telephone = form.cleaned_data['telephone']
            user_profile.campus = form.cleaned_data['campus']

            user_profile.save()

            return HttpResponseRedirect(reverse('UserProfile:profile'))

    else:
        default_data = {'name': user_profile.name,
                        'classes': user_profile.classes,
                        'bank_card': user_profile.bank_card,
                        'identity_card': user_profile.identity_card,
                        'telephone': user_profile.telephone,
                        'campus': user_profile.campus,
                        }
        form = ProfileForm(default_data)


    return render(request, 'account/profile_update.html', {'form': form, 'user': user})

用户更新资料需要用到表单,所以我们把表单单独放在forms.py, 代码如下所示。我们创建了两个表单:一个是更新用户资料时使用,一个是重写用户登录表单。

代码语言:javascript
复制
from django import forms
from .models import UserProfile

from UserProfile.models import CAMPUS_TYPE


class ProfileForm(forms.Form):
    name = forms.CharField(label='姓名', max_length=50, required=False)
    classes = forms.CharField(label='班级',max_length=50,required=False)
    bank_card = forms.CharField(label='中行卡号',max_length=50,required=False)
    identity_card = forms.CharField(label='身份证号',max_length=18,required=False)
    telephone = forms.CharField(label='联系方式',max_length=11,required=False)
    campus = forms.ChoiceField(label='校区',choices=CAMPUS_TYPE,required=False)


# 重写注册表单,注册的时候创建关联对象
class SignupForm(forms.Form):
    def signup(self, request, user):
        user_profile = UserProfile()
        user_profile.user = user
        user.save()
        user_profile.save()

再编写profile页面的模板

从github上面的django-allauth拉下来templates文件夹,放进UserProfile文件夹中。

随后在UserProfile/templates/accounts/目录下创建profile.htmlprofile_update文件。需要严格要求按照上面的目录结构来创建文件,因为allauth默认会在templates/account/文件夹下寻找模板文件。

profile.html

代码语言:javascript
复制
{% block content %}
{% if user.is_authenticated %}
<a href="{% url 'UserProfile:profile_update' %}">Update Profile</a> | <a href="{% url 'account_email' %}">Manage Email</a>  | <a href="{% url 'account_change_password' %}">Change Password</a> |
<a href="{% url 'account_logout' %}">Logout</a>
{% endif %}
<p>Welcome, {{ user.username }}.</p>


<h2>My Profile</h2>

<ul>
    <li>Name: {{ user.profile.name }} </li>
    <li>classes: {{ user.profile.classes }} </li>
    <li>bank_card: {{ user.profile.bank_card }} </li>
    <li>telephone: {{ user.profile.telephone }} </li>
</ul>


{% endblock %}

profile_update.html

代码语言:javascript
复制
{% block content %}
{% if user.is_authenticated %}
<a href="{% url 'UserProfile:profile_update' %}">Update Profile</a> | <a href="{% url 'account_email' %}">Manage Email</a>  | <a href="{% url 'account_change_password' %}">Change Password</a> |
<a href="{% url 'account_logout' %}">Logout</a>
{% endif %}
<h2>Update My Profile</h2>
 
<div class="form-wrapper">
   <form method="post" action="" enctype="multipart/form-data">
      {% csrf_token %}
      {% for field in form %}
           <div class="fieldWrapper">
        {{ field.errors }}
        {{ field.label_tag }} {{ field }}
        {% if field.help_text %}
             <p class="help">{{ field.help_text|safe }}</p>
        {% endif %}
           </div>
        {% endfor %}
      <div class="button-wrapper submit">
         <input type="submit" value="Update" />
      </div>
   </form>
</div>
 
 
{% endblock %}

然后就可以使用三板斧查看效果了

代码语言:javascript
复制
python manage.py makemigrations
python manage.yy migrate
python manage.py runserver

新注册了一个叫做小明的用户,注册能够自动跳转到profile页面。

至此,就基本完成了拓展用户模型的需求。

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 拓展用户模型(UserProfile)
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档