The project requirements
Users are divided into students, teachers and classes.
Administrators can add, delete, change and check these users after landing.
Database design and analysis
Students and classes ——————- many to one
Teacher and class ——————- many to many
Start project
1 Create a Django project user_Manager and add the App01 application
2 configuration setting. Py
Disable CSRF authentication and configure the static file path and session
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '0@&cx)%n! @x9u6-7pj+-y$dow1#&boejv#wo(gf$-sv_^(2enc'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin'.'django.contrib.auth'.'django.contrib.contenttypes'.'django.contrib.sessions'.'django.contrib.messages'.'django.contrib.staticfiles'.'app01.apps.App01Config',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware'.'django.contrib.sessions.middleware.SessionMiddleware'.'django.middleware.common.CommonMiddleware'.# Cancel CSRF validation
#'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware'.'django.contrib.messages.middleware.MessageMiddleware'.'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'user_manager.urls'
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',
],
},
},
]
WSGI_APPLICATION = 'user_manager.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3'.'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),}}# Password validation
# https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator'}, {'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator'}, {'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator'}, {'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',},]# Internationalization
# https://docs.djangoproject.com/en/2.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.0/howto/static-files/
STATIC_URL = '/static/'
Configure the static file path
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),# configuration session
SESSION_ENGINE = 'django.contrib.sessions.backends.db' # Engine (default)
SESSION_COOKIE_NAME = "sessionid" Sessionid = random string (default)
SESSION_COOKIE_PATH = "/" The path where the Session cookie is saved (default)
SESSION_COOKIE_DOMAIN = None # Session cookie saved domain name (default)
SESSION_COOKIE_SECURE = False # whether to transfer cookies over Https (default)
SESSION_COOKIE_HTTPONLY = True # whether Session cookies only support HTTP transmission (default)
SESSION_COOKIE_AGE = 1209600 # Session cookie expiration date (2 weeks) (default)
SESSION_EXPIRE_AT_BROWSER_CLOSE = False # Whether to close the browser and make the Session expire (default)
SESSION_SAVE_EVERY_REQUEST = False # whether to save Session on every request, default to save after modification (default)
Copy the code
3 Table design (Models.py under APP01)
Class table, student table, teacher table, administrator table
from django.db import models
class Classes(models.Model):
caption = models.CharField(max_length=32)
class Student(models.Model):
name = models.CharField(max_length=32)
email = models.CharField(max_length=32,null=True)
cls = models.ForeignKey('Classes',on_delete=None)
class Teacher(models.Model):
name = models.CharField(max_length=32)
cls = models.ManyToManyField('Classes')A third table is automatically generated here
class Administrator(models.Model):
username = models.CharField(max_length=32)
password = models.CharField(max_length=32)
Copy the code
Four generation table
Run the Terminal command
python manage.py makemigrations
python manage.py migrate
5 View the generated table
Click Database in the upper right corner of PyCharm and drag db.sqlite3 under the project to see it.
6 Login Function
login.html
<! DOCTYPE html> <html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
label{
width: 80px;
text-align: right;
display: inline-block;
}
</style>
</head>
<body>
<form action="login.html" method="post">
<div>
<label for="user"> User name: </label> <input ID ="user" type="text" name="user" />
</div>
<div>
<label for="pwd"> Password: </label> <input ID ="pwd" type="password" name="pwd" />
</div>
<div>
<label> </label>
<input type="submit" value="Login" />
<span style="color: red;">{{ msg }}</span>
</div>
</form>
</body>
</html>
Copy the code
views.py
# Create your views here.
from django.shortcuts import render,redirect,HttpResponse
from app01 import models
def login(request):
message = ""
v = request.session
print(type(v))
from django.contrib.sessions.backends.db import SessionStore
if request.method == "POST":
user = request.POST.get('user')
pwd = request.POST.get('pwd')
c = models.Administrator.objects.filter(username=user, password=pwd).count()
if c:
request.session['is_login'] = True
request.session['username'] = user
rep = redirect('/index.html')
return rep
else:
message = "Wrong username or password"
obj = render(request,'login.html', {'msg': message})
return obj
def logout(request):
request.session.clear()
return redirect('/login.html')
# a decorator
def auth(func):
def inner(request, *args, **kwargs):
is_login = request.session.get('is_login')
if is_login:
return func(request, *args, **kwargs)
else:
return redirect('/login.html')
return inner
@auth
def index(request):
current_user = request.session.get('username')
return render(request, 'index.html', {'username': current_user})
urls.py
from django.contrib import admin
from django.urls import path,re_path
from app01 import views
urlpatterns = [
path('admin/', admin.site.urls),
path('login.html', views.login),
path('index.html', views.index),
path('logout.html', views.logout),
]
Copy the code
Template page base.html
<! DOCTYPE html> <html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
body{
margin: 0;
}
.hide{
display: none;
}
.menu .item{
display: block;
padding: 5px 10px;
border-bottom: 1px solid #dddddd;
}
.menu .item:hover{
background-color: black;
color: white;
}
.menu .item.active{
background-color: black;
color: white;
}
.modal{
position: fixed;
top: 50%;
left: 50%;
width: 500px;
height: 400px;
margin-top: -250px;
margin-left: -250px;
z-index: 100;
background-color: white;
}
.remove{
position: fixed;
top: 50%;
left: 50%;
width: 400px;
height: 200px;
margin-top: -100px;
margin-left: -200px;
z-index: 100;
background-color: #c00;
}
.shade{
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: black;
opacity: 0.5;
z-index: 99;
}
.pagination a{
display: inline-block;
padding: 5px;
}
.pagination a.active{
background-color: black;
color: white;
}
</style>
{% block css %} {% endblock %}
</head>
<body>
<div style="height: 48px; background-color: black; color: white">
<div style="float: right"> username: {{username}} | < a href ="/logout.html"> logout </a></div> </div> <div> <div class="menu" style="position: absolute; top: 48px; left: 0; bottom:0; width: 200px; background-color: #eeeeee">
<a id="menu_class" class="item" href="/classes.html"> Class management </a> <a id="menu_student" class="item" href="/student.html"> Student administration </a> <a id="menu_teacher" class="item" href="/teacher.html""> </a> </div> <div style="position: absolute; top: 48px; left: 200px; bottom:0; right: 0; overflow: auto">
{% block content %} {% endblock %}
</div>
</div>
<script src="/ static/jquery - 2.1.4. Min. Js." "></script>
{% block js %} {% endblock %}
</body>
</html>
Copy the code
Home page index. HTML
{% extends "base.html"%} {% block CSS %} {% endblock %} {% block Content %} <h1> Welcome to use the most fashionable and fashionable user management center </h1> {% endblock %} {% block js %} {% endblock %}Copy the code
Start the project, add an administrator user to the database yourself, and log in to test.