1.创建Django框架
2.安装Django服务与mysqlclient服务
3.创建子应用
4.开启数据库服务,并创建一个接下来需要用的新数据库
(详细内容请见前几章节Django创建第一个应用程序
Django连接数据库)
主要配置INSTALLED_APPS 和DATABASES 数据库服务
"""
Django settings for 增查 project.
Generated by 'django-admin startproject' using Django 3.1.7.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'it38^ojb01ua^x%o8je*(!8udch8r!!!@p74^ra%3%(8jhq2%y'
# 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',
'stu'
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = '增查.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [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 = '增查.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'student',# 你自己的数据库名
'USER': 'root',# 用户名
'PASSWORD': 'root',# 密码
'HOST': 'localhost',# 本地ip
'PORT': 3306,# 端口号
}
}
# Password validation
# https://docs.djangoproject.com/en/3.1/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/3.1/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/3.1/howto/static-files/
STATIC_URL = '/static/'
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('stu/', include('stu.urls')),# 子应用
]
以上几步有哪里不懂的小伙伴可以看一下Django创建第一个应用程序
Django连接数据库
from django.urls import path
from stu import views
urlpatterns = [
path('login/', views.login),
]
不懂的小伙伴可以观看注释内的文字内容
from django.http import HttpResponse
from django.shortcuts import render
from stu.models import Student
def login(request):
# 判断请求方式
if (request.method == 'GET'):
# 如果是get请求直接返回页面
return render(request, 'login.html')
else:
# 如果是post请求做表单验证
sname = request.POST.get('sname')
spwd = request.POST.get('spwd')
# sigt是获取注册按钮,前端点击注册按钮就有返回值,没有点击就为空
sigt=request.POST.get('sigt')
# 获取数据库表中所有元素.相当于sql语句:select * from student
stus = Student.objects.all()
# 先判断是不是注册按钮
if(sigt != None):
# 是注册按钮就直接写入数据库
Student(sname=sname, spwd=spwd).save()
return HttpResponse('<h1>已为您注册成功!</h1>')
# 如果是登录按钮,就遍历数据库表中的内容
for i in stus:
if (i.sname == sname and i.spwd == spwd):
return render(request, 'index.html', {'stus': stus})
else:
return HttpResponse('<h1>请先注册!!</h1>')
from django.db import models
class Student(models.Model):
# 这里是模型类,这里跟数据库列名要保持一致
sname=models.CharField(max_length=10)
spwd=models.CharField(max_length=10)
class Meta:
db_table='stu'
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="/stu/login/" method="post">
{% csrf_token %}
用户名:<input type="text" name="sname"><br/>
密 码:<input type="password" name="spwd"><br/>
<input type="submit" value="登录">       
<input type="submit" value="注册" name="sigt">
</form>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<table border="1" cellspacing="1" cellpadding="1" width="300px">
<tr>
<th>编号</th>
<th>用户名</th>
<th>密码</th>
</tr>
{# Django框架可以在html页面中直接写Python代码,使用方式为{% 代码 %}#}
{% for i in stus %}
<tr>
{# 在页面中使用Python代码输出变量#}
<td>{{ i.id }}</td>
<td>{{ i.sname }}</td>
<td>{{ i.spwd }}</td>
</tr>
{% endfor %}
</table>
</body>
</html>
模板语法:
{%%}
循环:
{% for 变量 in 序列 %}
{% endfor %}
注释:
{# #}
判断:
{% if: %}
{% elif: %}
{% endif %}
模板变量:
{{}}
生成迁移文件: python manage.py makemigrations
执行迁移文件: python manage.py migrate stu
本章使用Django框架实现了对数据库的增加以及查询功能的实现,和html中的少量模板语法,实现方法不只这一种,各位感兴趣的小伙伴,可以去试一试.
有哪里不足或者有更好的建议,欢迎留言吐槽,有哪里不懂的小伙伴可以私信我,我会一一答复,感谢认可,感谢支持!