人生苦短,我要学python!
python也有框架,那就是Django,它是集成框架,这个框架可以执行所有的操作,不像SSM是由三个框架组成的。
首先,是在pycharm中新建Django项目。
注意:在新建时,目录下还有操作。
打开树形选项,写入项目的版块名,目的是为了插件式开发,各版块共同存在且互不影响,却又组成了一个大项目。
新建欧克后,有两个文件是自动打开的。
Django项目分为了三个文件夹。
第一个大文件夹是:Django项目的基本配置,它与Django项目同名
它的
扫描二维码关注公众号,回复:
3895717 查看本文章
__init__.py很重要!
# alt+enter回车
import pymysql
pymysql.install_as_MySQLdb()
这是pymysql的导包,即数据库连接包的配置。
接下来,是settings.py
"""
Django settings for DjangoWeb project.
Generated by 'django-admin startproject' using Django 2.1.2.
For more information on this file, see
https://docs.djangoproject.com/en/2.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.1/ref/settings/
"""
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.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'x5onoylzr5*th%mp&qolaaw$qa_$6!_1k$*!#9z-vsvv)y_5l_'
# 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',
'Student.apps.StudentConfig',
]
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 = 'DjangoWeb.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 = 'DjangoWeb.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
# 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
'NAME': 'cn',
'USER': 'root',
'PASSWORD': 'root',
'HOST': '127.0.0.1'
}
}
# Password validation
# https://docs.djangoproject.com/en/2.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/2.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/2.1/howto/static-files/
STATIC_URL = '/static/'
只需要注意databases
DATABASES是数据库配置信息
将它改为自己的格式,engine 改为你需要的数据库种类,其他的如:数据库名、用户、密码、连接地址。
接下来是urls.py
"""DjangoWeb URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from Student import views
urlpatterns = [
path('admin/', admin.site.urls),
# path('') http://127.0.0.1:8000/
path('', views.first),
path('first.html', views.first),
path('insert.html', views.insert),
path('insertUser.html', views.insertUser),
path('delete.html', views.delete),
path('update.html', views.update),
path('updateUser.html', views.updateUser),
]
先导入第二个大文件夹即所建的板块的views
urlpatterns:是路径
系统自动配置了一个admin的路径,这是后台会用到的。
path(‘’):为默认路径,项目一运行就会进入,调用views中的方法,注意方法后面不带括号。
第二个大文件夹,即所建的板块。
这里,
# This is an auto-generated Django model module.
# You'll have to do the following manually to clean this up:
# * Rearrange models' order
# * Make sure each model has one field with primary_key=True
# * Make sure each ForeignKey has `on_delete` set to the desired behavior.
# * Remove `managed = False` lines if you wish to allow Django to create, modify, and delete the table
# Feel free to rename the models, but don't rename db_table values or field names.
from django.db import models
# python manage.py inspectdb > student/models.py
class User(models.Model):
userid = models.AutoField(db_column='userId', primary_key=True) # Field name made lowercase.
username = models.CharField(db_column='userName', max_length=255, blank=True,
null=True) # Field name made lowercase.
usersay = models.CharField(db_column='userSay', max_length=255, blank=True, null=True) # Field name made lowercase.
class Meta:
managed = False
db_table = 'user'
这是对象的储存地。
配置好数据库连接后,在terminal控制台输入
python manage.py inspectdb > student/models.py
即可从MySQL中将表导入为对象,对象的属性名以models中的为准。
接下来:
from django.shortcuts import render
from django.shortcuts import HttpResponse
from django.shortcuts import redirect
from Student.models import *
# Create your views here.
def first(request):
users=User.objects.all()
count = users.__len__()
return render(request, 'first.html', context={'users': users, 'count': count})
# {% csrf_token %} Forbidden (403)
def delete(request):
uid=request.GET.get('uid')
User.objects.filter(userid=uid).delete()#找到则删除
return redirect('first.html')
def update(request):
uid = request.GET.get('uid')
user=User.objects.get(userid=uid)
return render(request,'update.html',context={'user':user})
def updateUser(request):
userId = request.POST.get('userId')
userName = request.POST.get('userName')
userSay = request.POST.get('userSay')
User.objects.filter(userid=userId).update(username=userName, usersay=userSay)
return redirect('first.html')
def insert(request):
return render(request, 'insert.html')
def insertUser(request):
userName = request.POST.get('userName')
userSay = request.POST.get('userSay')
User.objects.create(username=userName, usersay=userSay)
return redirect('first.html')#重定向
# def insert(request):
# if request.method=='POST':
# userName=request.POST.get('userName')
# userSay=request.POST.get('userSay')
# User.objects.create(username=userName,usersay=userSay)
# return redirect('first.html')
# else:
# return render(request, 'insert.html')
这是views,urls匹配到正确的路径后,会调用这里的方法。
调用数据,对象
.objects
然后,调用具体操作方法。
all:表中所有数据
第三个大文件夹,是HTML页面。
first:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>hello world</title>
</head>
<body>
用户管理
总数:{{ count }}
<a href="insert.html">新增用户</a>
<div align="center">
<table border="1">
<thead>
<th>编号</th>
<th>姓名</th>
<th>言论</th>
<th>删除</th>
<th>修改</th>
</thead>
<tbody>
{% for user in users %}
<tr>
<td>{{ user.userid }}</td>
<td>{{ user.username }}</td>
<td>{{ user.usersay }}</td>
<td><a href="delete.html?uid={{ user.userid }}">删除</a></td>
<td><a href="update.html?uid={{ user.userid }}">修改</a></td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</body>
</html>
insert:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>insert</title>
</head>
<body>
<div align="center">
<form action="insertUser.html" method="post">
{% csrf_token %}
姓名:<input type="text" name="userName"><br>
言论:<input type="text" name="userSay"><br>
<input type="submit" value="添加">
</form>
</div>
</body>
</html>
提交表单数据,必须
{% csrf_token %}
update:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>update</title>
</head>
<body>
<div align="center">
<form action="updateUser.html" method="post">
{% csrf_token %}
<input type="hidden" name="userId" value="{{ user.userid }}">
姓名:<input type="text" name="userName" value="{{user.username }}"><br>
言论:<input type="text" name="userSay" value="{{user.usersay }}"><br>
<input type="submit" value="添加">
</form>
</div>
</body>
</html>
非常好用!
期待python的爬虫!