1 创建python虚拟环境:
https://www.cnblogs.com/sd-xyy/p/12778391.html
//1 进入虚拟环境主目录: cd vir/ //2 创建新的虚拟环境: mkvirtualenv mycloud_notebook //3 进入新虚拟包:
cd mycloud_notebook/
//4 安装django pip install django==1.11.8 //5 查看已安装的python包: pip list
3 创建django项目:
django-admin startproject mycloud_notebook
4 进入项目文件夹, 并查看:
$ cd mycloud_notebook
manage.py mycloud_notebook
$ tree
5创建APP:
django-admin startapp note
django-admin startapp user
6 将app添加进配置文件:
""" mycloud_notebook/mycloud_notebook/settings.py: """#允许所有用户访问 ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ #添加 APP: 'note', 'user', ]
#关掉路由自动补全
APPEND_SLASH = False
7 在note 和 user 文件夹下各创建 urls.py文件:
from django.conf.urls import url from . import views urlpatterns = [ url(r'^login', views.mylogin), url(r'^logout', views.mylogout), ]
8 在 主路由表中 mycloud_notebook/mycloud_notebook/urls.py:
from django.conf.urls import url from django.contrib import admin
# 添加include from django.conf.urls import include from . import views urlpatterns = [ url(r'^admin/', admin.site.urls),
#分别导入APP中的urls文件: url(r'^note/', include('note.urls')), url(r'^user/', include('user.urls')),
#创建主页路由: url(r'^$', views.index), ]
9 在mycloud_notebook/mycloud_notebook/创建 views.py 文件
from django.http import HttpResponse from django.shortcuts import render
#创建主页处理函数: def index(request): return render(request, 'index.html', locals())
10 在 mycloud_notebook/创建 templates 文件夹 并创建模板
添加模板文件夹
mycloud_notebook/templates
note/templates/note
user/templates/user
11 在 settings.py 添加模板文件夹
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', ], }, }, ]
12 在 mycloud_notebook/templates创建 index.html
!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>主页</title> </head> <body> {% if request.session and request.session.userinfo %} 欢迎: {{ request.session.userinfo }} <a href="/user/logout">注销</a> {% else %} <a href="/user/login">登陆</a> <a href="/user/reg">注册</a> {% endif %} </body> </html>
13 在user/models.py 添加模型类
from django.db import models
# Create your models here.
# file: /user/models.py
class User(models.Model):
name = models.CharField('姓名', max_length=50)
password = models.CharField('密码', max_length=50)
def __str__(self):
return "用户:" + self.name
14在note/models.py 添加模型类
from django.db import models
# Create your models here.
# file : note/models.py
from user.models import User
class Note(models.Model):
title = models.CharField('标题', max_length=100,
default='')
content = models.TextField('内容', default='')
#auto_now_add=True 说明当数据库创建的时候会修改时间
create_time = models.DateTimeField('创建时间', auto_now_add=True)
#auto_now=True 说明当数据库 .save()的时候会修改时间
mod_time = models.DateTimeField('修改时间',
auto_now=True)
author = models.ForeignKey(User) # 一对多
def __str__(self):
return "笔记:" + self.title
15 创建数据库:
$ mysql -u root -p
$ show databases;
$ create database mywebdb default charset utf8 collate utf8_general_ci;
16 mysql 数据库配置
DATABASES = { 'default' : { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'mynote', # 数据库名称,需要自己定义 'USER': 'root', 'PASSWORD': '123456', # 管理员密码 'HOST': '127.0.0.1', 'PORT': 3306, } }
17 添加 mysql 支持
- 安装pymysql 模块
$ sudo pip install pymysql
$ sudo pip3 install mysqlclient # 非必须安装
- 修改项目中__init__.py 加入如下内容来提供pymysql引擎的支持
import pymysql pymysql.install_as_MySQLdb()
18 创建数据库原型: python3 manage.py makemigration
19 同步数据库: python3 manage.py migrate
20 创建超级用户:
$ python3 manage.py createsuperuser Username (leave blank to use 'tarena'): tarena # 此处输入用户名 Email address: laowei@tedu.cn # 此处输入邮箱 Password: # 此处输入密码(密码要复杂些,否则会提示密码太简单) Password (again): # 再次输入重复密码 Superuser created successfully. $
21 app.py中添加数据管理:
. 在应用app中的admin.py中导入注册要管理的模型models类, 如: ```python from . import models ``` 2. 调用 admin.site.register 方法进行注册,如: ```python from django.contrib import admin admin.site.register(自定义模型类) - 如: 在 bookstore/admin.py 添加如下代码对Book类进行管理 - 示例: ```python # file: bookstore/admin.py from django.contrib import admin # Register your models here. from . import models ... admin.site.register(models.Book) # 将Book类注册为可管理页面 ```
22 在数据表中添加类:
通过Meta内嵌类 定义模型类的属性及展现形式 - 模型类可以通过定义内部类class Meta 来重新定义当前模型类和数据表的一些属性信息 - 用法格式如下: ```python class Book(models.Model): title = CharField(....) class Meta: 1. db_table = '数据表名' - 该模型所用的数据表的名称。(设置完成后需要立马更新同步数据库) 2. verbose_name = '单数名' - 给模型对象的一个易于理解的名称(单数),用于显示在/admin管理界面中 3. verbose_name_plural = '复数名' - 该对象复数形式的名称(复数),用于显示在/admin管理界面中 class Book(models.Model): title = models.CharField(verbose_name="书名",max_length=50, default="") publish= models.CharField(verbose_name="出版社", max_length=100, default="") price= models.DecimalField(verbose_name="定价", max_digits=7, decimal_places=2,default=0) market_price= models.DecimalField(verbose_name="零售价", max_digits=7, decimal_places=2, default= 50.00) def __str__(self): show_str= " 书名:{0}, 出版社: {1}, 单价:{2}, 零售价{3} ".format(self.title, self.publish, self.price, self.market_price) return show_str class Meta: db_table=” my_book” verbose_name= "书名" verbose_name_plural="图书列表"
完整目录:
完整包目录:
完整代码:
$ mycloud_notebook/mycloud_notebook/__init__.py
import pymysql pymysql.install_as_MySQLdb()
$ mycloud_notebook/mycloud_notebook/setting.py
""" Django settings for mycloud_notebook project. Generated by 'django-admin startproject' using Django 1.11.8. 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 = '^wwpbr(jkbj3$zi88ero0d(d+5akh&qt8pl=^d4*-r%_!&%*)=' # 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', 'note', 'user', ] 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 = 'mycloud_notebook.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 = 'mycloud_notebook.wsgi.application' # Database # https://docs.djangoproject.com/en/1.11/ref/settings/#databases DATABASES = { # 'default': { # 'ENGINE': 'django.db.backends.sqlite3', # 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), # } 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'mynote', # 数据库名称,需要自己定义 'USER': 'root', # 修改为自己的用户名 'PASSWORD': '123456', # 管理员密码 'HOST': '127.0.0.1', # 修改自己的IP地址 '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 = 'zh-hans' 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/'
$ mycloud_notebook/mycloud_notebook/urls.py
from django.conf.urls import url from django.contrib import admin from django.conf.urls import include from . import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^note/', include('note.urls')), url(r'^user/', include('user.urls')), url(r'^$', views.index), ]
$ mycloud_notebook/mycloud_notebook/views.py
from django.http import HttpResponse from django.shortcuts import render def index(request): return render(request, 'index.html', locals())
$ mycloud_notebookmycloud_notebook ote emplates oteshowall.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>{{ user.name }}的笔记</title> </head> <body> {% for note in notes %} <div> 标题:{{note.title}} 日期 {{note.create_time}} <a href="/note/mod/{{note.id}}">修改</a> <a href="/note/del/{{note.id}}">删除</a> </div> {% endfor %} </body> </html>
$ mycloud_notebookmycloud_notebook oteadmin.py
from django.contrib import admin # Register your models here. from . import models admin.site.register(models.Note)
$ mycloud_notebookmycloud_notebook otemodels.py
from django.db import models # Create your models here. # file : note/models.py from user.models import User class Note(models.Model): title = models.CharField('标题', max_length=100, default='') content = models.TextField('内容', default='') create_time = models.DateTimeField('创建时间', auto_now_add=True) mod_time = models.DateTimeField('修改时间', auto_now=True) author = models.ForeignKey(User) # 一对多 def __str__(self): return "笔记:" + self.title
$ mycloud_notebookmycloud_notebook oteurls.py
from django.conf.urls import url from . import views urlpatterns = [ # 查看本人的全部笔记 url(r'^showall', views.showall), url(r'^new', views.new), # 新建笔记 url(r'^del/(d+)', views.delete), # 删除笔记 url(r'^mod/(d+)', views.modify), # 修改笔记 ]
$ mycloud_notebookmycloud_notebook oteviews.py
from django.shortcuts import render # Create your views here. from django.http import HttpResponse, Http404 from django.http import HttpResponseRedirect from user.models import User from . import models def showall(request): if hasattr(request, 'session') and 'userinfo' in request.session: # 此时用户已登陆 # 拿到用户id user_id = request.session['userinfo']['id'] # 根据当前登陆用户找到当前用户 user = User.objects.get(id=user_id) # 根据当前用户筛选出当前用户的笔记 notes = models.Note.objects.filter(author=user) return render(request, 'note/showall.html', locals()) else: raise Http404 def new(request): if hasattr(request, 'session') and 'userinfo' in request.session: # 此时用户已登陆 # 拿到用户id user_id = request.session['userinfo']['id'] # 根据当前登陆用户找到当前用户 user = User.objects.get(id=user_id) # 根据当前用户筛选出当前用户的笔记 anote = models.Note(author=user) import random anote.title = "自定义标题%d" % random.randrange(10000) anote.content = '这是随便写的内容' anote.save() return HttpResponse("OK") else: raise Http404 def delete(request, id): if hasattr(request, 'session') and 'userinfo' in request.session: # 此时用户已登陆 # 拿到用户id user_id = request.session['userinfo']['id'] # 根据当前登陆用户找到当前用户 user = User.objects.get(id=user_id) try: anote = models.Note.objects.get(author=user, id=id) anote.delete() return HttpResponseRedirect('/note/showall') except: return HttpResponse("删除失败") else: raise Http404 def modify(request, id): pass
$ mycloud_notebook/templates/index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>主页</title> </head> <body> {% if request.session and request.session.userinfo %} 欢迎: {{ request.session.userinfo }} <a href="/user/logout">注销</a> {% else %} <a href="/user/login">登陆</a> <a href="/user/reg">注册</a> {% endif %} </body> </html>
$ mycloud_cloud_notebookmycloud_notebookuser emplatesuserlogin.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>登陆</title> </head> <body> <form action="/user/login" method="post"> {% csrf_token %} <div> <lable>用户名</lable> <input type="text" name="username" value="{{ username }}"> </div> <div> <lable>密码</lable> <input type="password" name="password"> </div> <div> <lable for="id_remember">记住密码</lable> <input type="checkbox" name="remember" id="id_remember" value="1"> </div> <div> <input type="submit" value="登陆"> </div> </form> </body> </html>
$ mycloud_notebookmycloud_notebookuser emplatesuser egister.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>注册</title> <style> span { color: red; } </style> </head> <body> <form action="/user/reg" method="post"> {% csrf_token %} <div> <lable>用户名</lable> <input type="text" name="username"> <span>{{ username_error }}</span> </div> <div> <lable>密码</lable> <input type="password" name="password"> </div> <div> <lable>密码(重复)</lable> <input type="password" name="password2"> </div> <div> <input type="submit" value="注册"> </div> </form> </body> </html>
$ mycloud_notebookmycloud_notebookuseradmin.py
from django.contrib import admin # Register your models here. # 当前文件为: user/admin.py from . import models admin.site.register(models.User)
$ mycloud_notebookmycloud_notebookusermodels.py
from django.db import models # Create your models here. # file: /user/models.py class User(models.Model): name = models.CharField('姓名', max_length=50) password = models.CharField('密码', max_length=50) def __str__(self): return "用户:" + self.name
$ mycloud_notebookmycloud_notebookuserurls.py
from django.conf.urls import url from . import views urlpatterns = [ url(r'^login', views.mylogin), url(r'^logout', views.mylogout), ]
$ mycloud_notebookmycloud_notebookuserviews.py
from django.shortcuts import render from django.http import HttpResponseRedirect from django.http import HttpResponse # Create your views here. from . import models def mylogin(request): if request.method == 'GET': return render(request, 'user/login.html') elif request.method == 'POST': # 获取表单的数据 username = request.POST.get('username', '') password = request.POST.get('password', '') # 验证用户名,密码是否正确 try: user = models.User.objects.get(name=username, password=password) # 在当前连接的Session中记录当前用户的信息 request.session['userinfo'] = { "username": user.name, 'id': user.id } return HttpResponseRedirect('/') # 回到首页 except: return HttpResponse("登陆失败") def mylogout(request): '退出登陆' if 'userinfo' in request.session: del request.session['userinfo'] return HttpResponseRedirect('/') # 注销后跳转到主页 # def myregister(request): # if request.method == 'GET': # return render(request, 'userinfo/register.html') # elif request.method == 'POST': # username = request.POST.get('username', '') # password = request.POST.get('password', '') # password2 = request.POST.get('password2', '') # if username == '': # username_error = "用户名不能为空" # return render(request, 'userinfo/register.html', locals()) # if password == '': # return HttpResponse("密码不能为空") # if password != password2: # return HttpResponse('两次密码不一致!') # # 开始注册功能 # try: # from . import models # user = models.User.objects.create( # name=username, # password=password # ) # return HttpResponse("注册成功") # except: # return HttpResponse("注册失败")