作者: zifanwang 发布于2020-05-15
首先在userprofile/views.py中增加用户注册函数:
from userprofile.froms import UserLoginForm,UserRegisterForm
def user_register(request):
if request.method == 'POST':
user_register_form = UserRegisterForm(data=request.POST)
if user_register_form.is_valid():
new_user = user_register_form.save(commit=False)
# 设置密码
new_user.set_password(user_register_form.cleaned_data['password'])
new_user.save()
# 保存好数据后立即登录并返回博客列表页面
login(request, new_user)
return redirect("article:article_list")
else:
return HttpResponse("注册表单输入有误。请重新输入~")
elif request.method == 'GET':
user_register_form = UserRegisterForm()
context = { 'form': user_register_form }
return render(request, 'userprofile/register.html', context)
else:
return HttpResponse("请使用GET或POST请求数据")
再在userprofile/froms.py增加 UserRegisterForm:
class UserRegisterForm(forms.ModelForm):
# 复写 User 的密码
password = forms.CharField()
password2 = forms.CharField()
class Meta:
model = User
fields = ('username', 'email', 'password')
def clean_password2(self):
data = self.cleaned_data
if data.get('password') == data.get('password2'):
return data.get('password')
else:
raise forms.ValidationError("密码输入不一致,请重试。")
接下来编写模板和 urls.py 新建templates/userprofile/register.html并输入:
{% extends "base.html" %}
{% load static %}
{% block title %}
register
{% endblock title %}
{% block content %}
<div class="container">
<div class="row">
<div class="col-12">
<br>
<form method="post" action=".">
{% csrf_token %}
<div class="form-group col-md-4">
<label for="username">Username</label>
<input type="text" class="form-control" id="username" name="username" required>
</div>
<div class="form-group col-md-4">
<label for="email">Email</label>
<input type="text" class="form-control" id="email" name="email">
</div>
<div class="form-group col-md-4">
<label for="password">Password</label>
<input type="password" class="form-control" id="password" name="password" required>
</div>
<div class="form-group col-md-4">
<label for="password2">Password again</label>
<input type="password" class="form-control" id="password2" name="password2" required>
</div>
<button type="submit" class="btn btn-primary">submit</button>
</form>
{# #}
</div>
</div>
</div>
{% endblock content %}
接下来在登陆界面中增加注册入口 编写login.html:
{% extends "base.html" %}
{% load static %}
{% block title %}
Login
{% endblock title %}
{% block content %}
<div class="container">
<div class="row">
<div class="col-12">
<br>
<form method="post" action=".">
{% csrf_token %}
<div class="form-group">
<label for="username">Username</label>
<input type="text" class="form-control" id="username" name="username">
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" class="form-control" id="password" name="password">
</div>
<button type="submit" class="btn btn-primary">Login</button>
</form>
<h5>No account yet?</h5>
<h5>Click <a href='{% url "userprofile:register" %}'>here</a> to register.</h5>
<br>
</div>
</div>
</div>
{% endblock content %}
最后在userprofile/urls.py中新增注册路由:
path('register/', views.user_register, name="register"),
然后我们启动重启服务器(python manage.py runserver)打开登陆界面http://127.0.0.1:8000/userprofile/login/:
点击here:
接着填写注册信息 点击提交后就可以看见成功注册并且自动登陆了。
编写userprofile/views.py:
from django.contrib.auth.models import User
# 引入验证登录的装饰器
from django.contrib.auth.decorators import login_required
...
@login_required(login_url='/userprofile/login/')
def user_delete(request, id):
user = User.objects.get(id=id)
if request.user == user:
logout(request)
user.delete()
return redirect("article:article_list")
else:
return HttpResponse("你没有删除操作的权限。")
@login_required是一个装饰器,就是 @login_required要求调用user_delete()函数时,用户必须登陆如果不登陆则不执行函数并且将重定向到 /userprofile/login/地址去。 然后改写templates/header.html,新增删除用户入口,并且添加弹窗组件的代码:
<head>
{% if user.is_authenticated %}
<script>
function user_delete() {
var r=confirm("Wanna delete this user?");
if (r==true)
{
window.location='{% url "userprofile:delete" user.id %}';
}
}
</script>
{% endif %}
</head>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<div class="container">
<a class="navbar-brand" href="#">My Site</a>
<div>
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link" href="{% url 'article:article_list' %}">Article</a>
</li>
<li class="nav-item">
<a class="nav-link" href="{% url 'article:article_create' %}">New</a>
</li>
{% if user.is_authenticated %}
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
{{ user.username }}
</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdown">
<a class="dropdown-item" href="{% url "userprofile:logout" %}">Exit</a>
<a class="dropdown-item" href="#" onclick="user_delete()">Delete</a>
</div>
</li>
{% else %}
<li class="nav-item">
<a class="nav-link" href="{% url 'userprofile:login' %}">Login</a>
</li>
{% endif %}
</ul>
</div>
</div>
</nav>
最后修改userprofile/urls.py:
path('delete/<int:id>/', views.user_delete, name='delete'),
看一下效果:
点击删除用户(注意请新注册一个用户并删除它,不要删除root)就可以删除用户了