#用Django写的一套增删改查模型
# 文件夹 mysite
# 1 __init__.py
import pymysql
pymysql.install_as_MySQLdb()
# 2 settings.py
"""
Django settings for mysite project.
Generated by 'django-admin startproject' using Django 1.11.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/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/1.11/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '2xz&6djy#=mt1+j$msy*0z#nm+d(7p5ib0-6cs5z2zcu*pvk%6'
# 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',
'myweb'
]
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 = 'mysite.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 = 'mysite.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'mydb',#选择数据库的名,请确认你的mysql中有这个库
'USER': 'root',
'PASSWORD': '123456',
'HOST': 'localhost',
'PORT': '3306',
}
}
# Password validation
# https://docs.djangoproject.com/en/1.11/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/1.11/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/1.11/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
# 3 urls.py
"""mysite URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url,include
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^', include('myweb.urls')),
]
# 4 wsgi.py
"""
WSGI config for mysite project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")
application = get_wsgi_application()
# 文件夹 myweb
# 1 admin.py
from django.contrib import admin
# 2 apps.py
from django.apps import AppConfig
class MywebConfig(AppConfig):
name = 'myweb'
# 3 models.py
from django.db import models
# Create your models here.
class Users(models.Model):
username = models.CharField(max_length=32)
password = models.CharField(max_length=32)
email = models.CharField(max_length=32)
age = models.IntegerField(default=18)
sex = models.IntegerField(default=1)
# 4 tests.py
from django.test import TestCase
# 5 urls.py
"""mysite URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index,name='index'),
# 用户管理 模型的实战操作
# 显示用户的添加页面
url(r'^useradd$', views.useradd,name='useradd'),
# 执行数据的添加
url(r'^userinsert$', views.userinsert,name='userinsert'),
# 显示用户数据列表
url(r'^userindex$', views.userindex,name='userindex'),
# 执行用户的删除操作
# url(r'^userdel$', views.userdel,name='userdel'),
url(r'^userdel/(?P<uid>[0-9]+)$', views.userdel,name='userdel'),
# 显示编辑页面
url(r'^useredit/(?P<uid>[0-9]+)$', views.useredit,name='useredit'),
# 执行用户的编辑
url(r'^userupdate$', views.userupdate,name='userupdate'),
]
# 6 views.py
from django.shortcuts import render, redirect
from django.core.urlresolvers import reverse
from django.http import HttpResponse
from .models import Users
# Create your views here.
# 首页
def index(request):
# 响应模板
return render(request, 'index.html')
# 显示添加的表单页面
def useradd(request):
# 返回一个模板
return render(request, 'user/add.html')
# 执行用户数据的添加
def userinsert(request):
# 接受数据
# uname = request.POST['usernames']
# uname = request.POST.get('usernames','')
# age = request.POST.get('age','abc')
# print(age)
# print(type(age))
try:
# 实例化模型对象
db = Users()
db.username = request.POST.get('username', '')
db.password = request.POST.get('password', '')
db.email = request.POST.get('email', '')
db.age = request.POST.get('age', 28)
db.sex = request.POST.get('sex', 0)
db.save()
# redirect重定向 reverse反向解析url地址
# return redirect(reverse('userindex'))
# 执行一段js代码,用js进行重定向
# return HttpResponse('<script>alert("添加成功");location.href = "/userindex"; </script>')
# 加载一个提醒信息的跳转页面
context = {'info': '数据添加成功', 'u': '/userindex'}
return render(request, 'info.html', context)
except:
# context = {'info':'数据添加失败'}
# redirect重定向 reverse反向解析url地址
return redirect(reverse('useradd'))
# 响应内容
# return HttpResponse(context['info'])
# 显示用户数据的列表页
def userindex(request):
# 查询所以用户数据[{}]
db = Users.objects.all()
# 分配变量
context = {'userlist': db}
# 返回一个模板
return render(request, 'user/index.html', context)
# 执行用户的数据删除
def userdel(request, uid):
try:
# 获取当前用户对象
db = Users.objects.get(id=uid)
# 执行删除
db.delete()
# return HttpResponse('删除成功'+uid)
return HttpResponse('<script>alert("删除成功");location.href = "/userindex"; </script>')
except:
# return HttpResponse('删除失败'+uid)
return HttpResponse('<script>alert("删除失败");location.href = "/userindex"; </script>')
# 显示编辑页
def useredit(request, uid):
# 获取当前用户对象 {}
db = Users.objects.get(id=uid)
# 分配数据
context = {'user': db}
# 返回模板
return render(request, 'user/edit.html', context)
# 执行编辑
def userupdate(request):
try:
# 获取当前用户对象
db = Users.objects.get(id=request.POST['uid'])
# 给属性重新赋值
db.username = request.POST['username']
db.email = request.POST['email']
db.age = request.POST['age']
db.sex = request.POST['sex']
# 执行修改
db.save()
# 修改成功
return HttpResponse('<script>alert("修改成功");location.href = "/userindex"; </script>')
except:
# 修改失败
return HttpResponse('<script>alert("修改失败");location.href = "/userindex"; </script>')
# 子文件夹 migrations
# 0001__initial.py
# -*- coding: utf-8 -*-
# Generated by Django 1.11.8 on 2018-02-07 01:14
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Users',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('username', models.CharField(max_length=32)),
('password', models.CharField(max_length=32)),
('email', models.CharField(max_length=32)),
('age', models.IntegerField(default=18)),
('sex', models.IntegerField(default=1)),
],
),
]
# 文件夹 static
/home/hanbing/作业/photo/static/favicon.ico
# 文件夹 templates
# 1 add.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>用户添加</title>
</head>
<body>
<!-- <form action="/userinsert" method=""> -->
<form action="{% url 'userinsert' %}" method="post">
{% csrf_token %}
用户名: <input type="text" name="username"><br>
密码: <input type="password" name="password"><br>
邮箱: <input type="email" name="email"><br>
年龄: <input type="number" name="age"><br>
性别: <input type="radio" name="sex" value="0">女
<input type="radio" name="sex" value="1">男
<br>
<button >添加</button>
</form>
</body>
</html>
# 2 index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>首页</title>
<link rel="shortcut icon" href="/static/favicon.ico" type="image/x-icon" />
</head>
<body>
<h1>网站首页</h1>
<ul>
<li><a href="{% url 'userindex' %}" style="text-decoration:none">用户管理</a></li>
</ul>
</body>
</html>
# 3 info.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>提醒信息</title>
</head>
<body>
<center>
<h3>{{ info }}</h3>
</center>
<script type="text/javascript">
setTimeout(function(){
location.href = '{{ u }}';
},2000)
</script>
</body>
</html>
# 子文件夹 user
# 1 add.html
< !DOCTYPE
html >
< html >
< head >
< meta
charset = "UTF-8" >
< title > 用户添加 < / title >
< / head >
< body >
< !-- < form
action = "/userinsert"
method = "" > -->
< form
action = "{% url 'userinsert' %}"
method = "post" >
{ % csrf_token %}
用户名: < input
type = "text"
name = "username" > < br >
密码: < input
type = "password"
name = "password" > < br >
邮箱: < input
type = "email"
name = "email" > < br >
年龄: < input
type = "number"
name = "age" > < br >
性别: < input
type = "radio"
name = "sex"
value = "0" > 女
< input
type = "radio"
name = "sex"
value = "1" > 男
< br >
< button > 添加 < / button >
< / form >
< / body >
< / html >
# 2 idit.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>用户编辑</title>
</head>
<body>
<!-- <form action="/userinsert" method=""> -->
<form action="{% url 'userupdate' %}" method="post">
{% csrf_token %}
<!-- 用户id -->
<input type="hidden" name="uid" value="{{ user.id }}">
用户名: <input type="text" name="username" value="{{ user.username }}"><br>
密码: <input disabled type="password" name="password" value="{{ user.password }}"><br>
邮箱: <input type="email" name="email" value="{{ user.email }}"><br>
年龄: <input type="number" name="age" value="{{ user.age }}"><br>
性别: <input type="radio" {% if user.sex == 0 %} checked {% endif %} name="sex" value="0">女
<input type="radio" {% if user.sex == 1 %} checked {% endif %} name="sex" value="1">男
<br>
<button >修改</button>
</form>
</body>
</html>
# 3 index.html
< !DOCTYPE
html >
< html >
< head >
< meta
charset = "UTF-8" >
< title > 用户列表 < / title >
< / head >
< body >
< center
style = "margin-top: 200px" >
< h4 > < a
href = "{% url 'useradd' %}"
style = "text-decoration:none" > 添加用户 < / a > < / h4 >
< table
border = "1"
width = "700"
cellspacing = "0" >
< tr
align = "center" >
< th > id编号 < / th >
< th > 用户名 < / th >
< th > 邮箱 < / th >
< th > 年龄 < / th >
< th > 性别 < / th >
< th > 操作 < / th >
< / tr >
{ %
for v in userlist %}
< tr
align = "center" >
< td > {{v.id}} < / td >
< td > {{v.username}} < / td >
< td > {{v.email}} < / td >
< td > {{v.age}} < / td >
< td >
{ % if v.sex == 0 %}
女
{ % else %}
男
{ % endif %}
< / td >
< td >
< a
href = "{% url 'userdel' v.id %}"
style = "text-decoration:none" > 删除 < / a >
|
< a
href = "{% url 'useredit' v.id %}"
style = "text-decoration:none" > 修改 < / a >
< / td >
< / tr >
{ % endfor %}
< / table >
< / center >
< / body >
< / html >
# manage.py
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")
try:
from django.core.management import execute_from_command_line
except ImportError:
# The above import may fail for some other reason. Ensure that the
# issue is really that Django is missing to avoid masking other
# exceptions on Python 2.
try:
import django
except ImportError:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
)
raise
execute_from_command_line(sys.argv)
兄弟连学python
Python学习交流、资源共享群:563626388 QQ