前几篇文章已经把用户系统的基本功能差不多实现了,这篇文章记录下如何扩展用户model实现添加用户签名字段。
1、创建用户APP并添加到全局settings.py
root@jerryls-site1:/home/mysite/apps# django-admin startapp myauth
2、修改用户model
修改myauth文件夹中的model.py文件如下:
from django.db import models
from django.contrib.auth.models import AbstractUser
# Create your models here.
class Myuser(AbstractUser):
# 添加个性签名字段
signature = models.CharField(max_length=50, blank=True, null=True, verbose_name="签名")
def __str__(self):
return self.username
修改完成后我们同步数据库,会报错:
auth.User.groups: (fields.E304) Reverse accessor for 'User.groups' clashes with reverse accessor for 'Myuser.groups'.
HINT: Add or change a related_name argument to the definition for 'User.groups' or 'Myuser.groups'.
auth.User.user_permissions: (fields.E304) Reverse accessor for 'User.user_permissions' clashes with reverse accessor for 'Myuser.user_permissions'.
HINT: Add or change a related_name argument to the definition for 'User.user_permissions' or 'Myuser.user_permissions'.
myauth.Myuser.groups: (fields.E304) Reverse accessor for 'Myuser.groups' clashes with reverse accessor for 'User.groups'.
HINT: Add or change a related_name argument to the definition for 'Myuser.groups' or 'User.groups'.
myauth.Myuser.user_permissions: (fields.E304) Reverse accessor for 'Myuser.user_permissions' clashes with reverse accessor for 'User.user_permissions'.
HINT: Add or change a related_name argument to the definition for 'Myuser.user_permissions' or 'User.user_permissions'.
此时,我们需要在全局settings.py下重载我们的“AUTH_USER_MODEL”:
# 重载auth_model
AUTH_USER_MODEL = 'myauth.Myuser'
其中myauth是我们app的名字,Myuser是我们的model。
有时候,还会遇到下面的错误:
Traceback (most recent call last):
File "./manage.py", line 15, in <module>
execute_from_command_line(sys.argv)
File "/usr/local/lib/python3.5/dist-packages/django/core/management/__init__.py", line 381, in execute_from_command_line
utility.execute()
File "/usr/local/lib/python3.5/dist-packages/django/core/management/__init__.py", line 375, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/usr/local/lib/python3.5/dist-packages/django/core/management/base.py", line 316, in run_from_argv
self.execute(*args, **cmd_options)
File "/usr/local/lib/python3.5/dist-packages/django/core/management/base.py", line 353, in execute
output = self.handle(*args, **options)
File "/usr/local/lib/python3.5/dist-packages/django/core/management/base.py", line 83, in wrapped
res = handle_func(*args, **kwargs)
File "/usr/local/lib/python3.5/dist-packages/django/core/management/commands/makemigrations.py", line 103, in handle
loader.check_consistent_history(connection)
File "/usr/local/lib/python3.5/dist-packages/django/db/migrations/loader.py", line 297, in check_consistent_history
connection.alias,
django.db.migrations.exceptions.InconsistentMigrationHistory: Migration account.0001_initial is applied before its dependency myauth.0001_initial on database 'default'.
此时,删掉全局下的db.sqlite3数据库文件重新同步就可以了。
root@jerryls-site1:/home/mysite# rm db.sqlite3
root@jerryls-site1:/home/mysite# ./manage.py makemigrations
root@jerryls-site1:/home/mysite# ./manage.py migrate
3、创建forms.py文件
在myauth文件夹下创建forms.py文件,添加如下代码:
# -*- coding: utf-8 -*-
from django import forms
from .models import Myuser
class ProfileForm(forms.ModelForm):
class Meta:
model = Myuser
fields = ['signature'] #只显示model中指定的字段
4、创建user_profile.html文件
我们需要创建一个user_profile.html文件来显示用户的用户名、邮箱、以及个性签名。同样按照之前的目录创建规则,放在myauth/templates/myauth目录下。代码如下:
{% extends "blog/base.html" %}
{% load static %}
{% block base_content %}
<style>
.col-center-block {
float: none;
display: block;
margin: 0 auto;
/* margin-left: auto; margin-right: auto; */
}
</style>
<div class="container">
<div class="row">
<div class="col-xs-6 col-md-4 col-center-block">
<ul class="list-group">
<li class="list-group-item" style="border:0px">
<h4><span>用户名:</span><span>{{user.username}}</span> </h4>
</li>
<li class="list-group-item" style="border:0px">
<h4><span>邮 箱:</span><span>{{user.email}}</span> </h4>
</li>
<li class="list-group-item" style="border:0px">
<h4><span>签 名:</span>{{user.signature}}</h4>
</li>
<a class="pull-right btn btn-primary" style="margin-right: 20px" href="{% url 'account_change_password' %}">修改密码</a>
</ul>
</div>
</div>
</div>
{% endblock %}
在这里我顺便加了个修改密码的链接“{% url 'account_change_password' %}”,这些语法很简单,不多BB。
5、添加view视图
修改myauth文件夹下的view.py代码如下,作用就是返回用户资料的html页面:
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
# Create your views here.
#需要登陆才可以
@login_required
def profile_view(request):
return render(request,'myauth/user_profile.html')
6、添加路由
路由添加由于新建了一个APP,我们需要添加两处路由:
1)myauth下添加urls.py文件,代码如下:
# -*- coding: utf-8 -*-
from .views import profile_view,update_profile_view
from django.urls import path
app_name = '[myauth]'
urlpatterns = [
path('profile/', profile_view,name='profile_url'),
]
2)全局路由下添加整个myauth APP的路由:
from django.contrib import admin
from django.urls import path
from django.conf.urls import include
urlpatterns = [
path('admin/', admin.site.urls),
path('accounts/', include('allauth.urls')),
path('accounts/', include('myauth.urls', namespace = 'myauth')),
path('', include('blog.urls', namespace = 'blog')),
]
此时运行博客,登陆成功后,访问/accounts/profile则会显示用户信息。
为了方便,我把它加到导航栏右上角下拉列表里。
<ul class="dropdown-menu">
<li><a href="{% url 'myauth:profile_url' %}">个人中心</a></li>
<li><a href="#">下拉2</a></li>
<li><a href="#">下拉3</a></li>
<li role="separator" class="divider"></li>
<li><a href="{% url 'account_logout' %}">退出</a></li>
</ul>
最终效果如下:
此处我们没有填写签名字段,所以显示None。接下来我们继续添加一个页面,用于修改签名。
步骤与上面类似,流程基本是:新建模板文件 --> 添加view --> 修改路由 --> 起飞!
7、添加update_profile.html文件
添加update_profile.html模板文件,代码如下:
{% extends "blog/base.html" %}
{% load static %}
{% block base_content %}
<style>
.col-center-block {
float: none;
display: block;
margin: 0 auto;
/* margin-left: auto; margin-right: auto; */
}
</style>
<div class="container">
<div class="row">
<div class="col-xs-6 col-md-4 col-center-block">
<form class="update_profile", method="post" enctype="multipart/form-data" action="{% url 'myauth:update_profile_url' %}">
{% csrf_token %}
{{ form.as_p }}
<button class="pull-right btn btn-primary" type="submit">确认更新</button>
</form>
</div>
</div>
</div>
{% endblock %}
一个form表单,post方法,用来将我们填写的个性签名传入view视图处理。
8、添加view视图
对前端post方法传来的数据,我们需要进行表单校验,并保存至数据库。myauth下的views.py 添加代码如下:
from django.shortcuts import render,redirect
from django.contrib.auth.decorators import login_required
from .forms import ProfileForm
# Create your views here.
#需要登陆才可以
@login_required
def update_profile_view(request):
if request.method == 'POST':
# request.FILES for upload files
form = ProfileForm(request.POST,request.FILES,instance=request.user)
if form.is_valid():
form.save()
return redirect('myauth:profile_url')
else:
# POST
form = ProfileForm(instance = request.user)
return render(request,'myauth/update_profile.html',context={'form':form})
9、添加路由
将资料更新界面添加路由,并在个人资料的界面添加一个按钮用来跳转:
# -*- coding: utf-8 -*-
from .views import profile_view,update_profile_view
from django.urls import path
app_name = '[myauth]'
urlpatterns = [
path('profile/', profile_view,name='profile_url'),
path('profile/update', update_profile_view,name='update_profile_url'),
]
<a class="pull-right btn btn-primary" style="margin-right: 20px" href="{% url 'myauth:update_profile_url' %}">修改资料</a>
最终实现界面如下:
以上流程就是添加一个字段的简单举例,其他字段类似添加。今晚先写这些吧,改天再记录下关于用户头像的自定义上传。写着写着,博主发现之前很多东西都快忘记了,真的是好记性不如烂笔头,哦,不对!是烂键盘~
《django 建站历程系列文章》