要实现功能:用户名信息在每个页面都要保持展示状态
下载地址在文章尾
项目结构
1,setting.py中更改内容:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'front',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
# 'django.middleware.csrf.CsrfViewMiddleware', #注释掉csrf
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
#basedir更改 及注册上下文处理器
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR,'templates/')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'front.context_processors.front_user'
],
},
},
]
先写models.py 构建模型
from django.db import models
class User(models.Model):
username = models.CharField(max_length=50)
password = models.CharField(max_length=10)
telephone = models.CharField(max_length=11)
#写完要在shell命令中敲入:
python manage.py makemigrations
python manage.py migrate
再写视图views.py
from django.shortcuts import render, redirect,reverse
from django.views.generic import View
from .form import SigninForm,RegisterForm
from .models import User
def test(request):
return render(request,'index.html')
class SigninView(View):
def get(self,request):
return render(request,'signin.html')
def post(self,request):
form = SigninForm(request.POST)
if form.is_valid():
username = form.cleaned_data.get('username')
password = form.cleaned_data.get('password')
user = User.objects.filter(username=username,password=password).first()
if user:
request.session['userid']=user.id
return redirect(reverse('index'))
else:
print('用户名或密码错误')
return redirect(reverse('signin'))
else:
print(form.errors.get_json_data())
return redirect(reverse('signin'))
class RegisterView(View):
def get(self,request):
return render(request,'register.html')
def post(self,request):
form = RegisterForm(request.POST)
if form.is_valid():
form.save()
return redirect(reverse('signin'))
else:
print(form.errors.get_json_data())
return redirect(reverse('register'))
写视图函数过程中,会同时把几个html文件写好
先写base.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>base</title>
<!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<body>
<nav class="navbar navbar-default">
<div class="container-fluid">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="{% url 'index' %}">首页</a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav">
<li><a href="#">Link <span class="sr-only">(current)</span></a></li>
<li><a href="#">Link</a></li>
</ul>
<ul class="nav navbar-nav navbar-right">
{% if front_user %}
<li><a href="#">{{ front_user.username }}</a></li>
{% else %}
<li><a href="{% url 'register' %}">注册</a></li>
<li><a href="{% url 'signin' %}">登录</a></li>
{% endif %}
</ul>
</div><!-- /.navbar-collapse -->
</div><!-- /.container-fluid -->
</nav>
{% block body %}
{% endblock %}
</body>
</html>
再写其他继承类:
index.html
{% extends 'base.html' %}
{% block body %}
首页
{% endblock %}
register.html
{% extends 'base.html' %}
{% block body %}
<form action="" method="post">
<table>
<tr>
<td>用户名:</td>
<td><input type="text" name="username"></td>
</tr>
<tr>
<td>密码:</td>
<td><input type="password" name="password"></td>
</tr>
<tr>
<td>再次输入密码:</td>
<td><input type="password" name="password_repeat"></td>
</tr>
<tr>
<td>手机号码:</td>
<td><input type="text" name="telephone"></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="submit"></td>
</tr>
</table>
</form>
{% endblock %}
sign.html
{% extends 'base.html' %}
{% block body %}
<form action="" method="post">
<table>
<tr>
<td>用户名:</td>
<td><input type="text" name="username"></td>
</tr>
<tr>
<td>密码:</td>
<td><input type="password" name="password"></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="submit"></td>
</tr>
</table>
</form>
{% endblock %}
写form验证表单类
forms.py
from django import forms
from .models import User
class SigninForm(forms.ModelForm):
class Meta:
model=User
fields=['username','password']
class RegisterForm(forms.ModelForm):
class Meta:
model=User
fields='__all__'
password_repeat = forms.CharField(max_length=10,min_length=6)
def clean(self):
password_repeat = self.cleaned_data.get('password_repeat')
password = self.cleaned_data.get('password')
if password!=password_repeat:
raise forms.ValidationError(message='两次密码输入不一致')
return self.cleaned_data
url.py内容
from django.urls import path
from front import views
urlpatterns = [
path('',views.test,name='index'),
path('signin/',views.SigninView.as_view(),name='signin'),
path('register/',views.RegisterView.as_view(),name='register')
]
最后写出上下文处理器,大功告成
from .models import User
def front_user(request):
user_id = request.session.get('userid')
context={}
if user_id:
try:
user = User.objects.get(pk=user_id)
context['front_user']=user
except:
pass
return context