从之前的学习我们发现,一直在blog
应用中进行开发。本章开始新建另一个App来开发,介绍Django的身份认证模块,实现用户登录、注册、注销。
为了实现用户登录、退出、注册等功能,从而进行用户管理,创建一个新的应用。
python manage.py startapp accounts
然后我们就多了一个accounts
目录,然后在/myblog/settings.py
中对新应用进行配置。
INSTALLED_APPS = [
...,
'blog',
'accounts',
]
在./accounts目录中创建urls.py
文件,然后设置本应用中的路径。
from django.urls import path
from . import views
app_name = "accounts"
urlpatterns = [
path('login/', views.user_login, name='user_login'),
]
然后在./myblog/urls.py
配置accounts
应用的URL配置:
from django.contrib import admin
from django.urls import path, include
from django.conf.urls import url
from blog import views
urlpatterns = [
path('admin/', admin.site.urls),
url(r'^$', views.home, name='home'),
path('<int:article_id>/', views.blog_article),
path('accounts/', include('accounts.urls', namespace='accounts')), # 新增
]
基本配置到位,接下来我们设计用户登录界面:
在./account
目录下新建forms.py
,代码如下:
from django import forms
class LoginForm(forms.Form):
username = forms.CharField()
password = forms.CharField(widget=forms.PasswordInput)
编辑./account/views.py
文件,实现user_login()
的视图函数:
from django.shortcuts import render, HttpResponse
from django.contrib.auth import authenticate, login
from . forms import LoginForm
# Create your views here.
def user_login(request):
if request.method == "POST":
login_form = LoginForm(request.POST)
if login_form.is_valid():
cd = login_form.cleaned_data
user = authenticate(username=cd['username'], password=cd['password'])
if user:
login(request, user)
return HttpResponse("欢迎你,登录成功")
else:
return HttpResponse("抱歉,用户名或者密码错误")
else:
return HttpResponse("登录非法")
else:
login_form = LoginForm()
return render(request, "accounts/login.html", {"form": login_form})
在./templates/accounts/login.html
模板,代码如下:
{% extends "base.html" %}
{% block title %}登录{% endblock %}
{% block content %}
<div class="container text-center" >
<h1>用户登录</h1>
<p>
输入你的用户名和密码
</p>
<form action="." method="post">
{% csrf_token %}
{{ form.as_p }}
<p><input type="submit" value="登录"></p>
</form>
</div>
{% endblock %}
修改./templates/base.html
,代码如下:
{% load staticfiles %}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>{% block title %}{% endblock %}</title>
<link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}">
</head>
<body>
<div id="header">
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<div class="container" >
<a class="navbar-expand" href="{% url 'home' %}">主页</a>
<ul class="nav navbar-nav navbar-light" style="margin-right: 10px">
<li><a href="{% url 'accounts:user_login' %}">登录</a> </li>
</ul>
</div>
</nav>
</div>
<div class="container">
<div id="content">
{% block content %}
{% endblock %}
</div>
</div>
</body>
</html>