python学习之web框架--Django 002
Django连接mysql数据库
涉及的内容有:1,创建app,
2,注册app
3, 逆向生成models.py
4,增删改查数据
5,结合前端提交数据保存到数据库
连接数据库:
步骤1,settings.py设置数据库连接信息
步骤2,安装mysqlclient (mysql客户端)
pip install mysqlclient
步骤3,启动项目
到现在,启动程序不报错,接下来建立数据表与实体(models.py中的类)的联系
步骤4,新建app,名字为Models
idea terminal 执行:python manage.py startapp Models
或者:
效果:
步骤5:通过数据库逆向获得models.py需要的实体类代码
在idea terminal 执行:python manage.py inspectdb
则会将生成的实体类代码输出到控制台
将其复制拷到models.py中:(tb_* 是我在navicat里面生成的表,其余的是自动生成的,似乎是用来记录其他信息的,不需要管)
# Create your models here.
# 类名对应表名,如果不指定id,会自动在数据表生成主键
# 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
class AuthGroup(models.Model):
name = models.CharField(unique=True, max_length=80)
class Meta:
managed = False
db_table = 'auth_group'
class AuthGroupPermissions(models.Model):
group = models.ForeignKey(AuthGroup, models.DO_NOTHING)
permission = models.ForeignKey('AuthPermission', models.DO_NOTHING)
class Meta:
managed = False
db_table = 'auth_group_permissions'
unique_together = (('group', 'permission'),)
class AuthPermission(models.Model):
name = models.CharField(max_length=255)
content_type = models.ForeignKey('DjangoContentType', models.DO_NOTHING)
codename = models.CharField(max_length=100)
class Meta:
managed = False
db_table = 'auth_permission'
unique_together = (('content_type', 'codename'),)
class AuthUser(models.Model):
password = models.CharField(max_length=128)
last_login = models.DateTimeField(blank=True, null=True)
is_superuser = models.IntegerField()
username = models.CharField(unique=True, max_length=150)
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=150)
email = models.CharField(max_length=254)
is_staff = models.IntegerField()
is_active = models.IntegerField()
date_joined = models.DateTimeField()
class Meta:
managed = False
db_table = 'auth_user'
class AuthUserGroups(models.Model):
user = models.ForeignKey(AuthUser, models.DO_NOTHING)
group = models.ForeignKey(AuthGroup, models.DO_NOTHING)
class Meta:
managed = False
db_table = 'auth_user_groups'
unique_together = (('user', 'group'),)
class AuthUserUserPermissions(models.Model):
user = models.ForeignKey(AuthUser, models.DO_NOTHING)
permission = models.ForeignKey(AuthPermission, models.DO_NOTHING)
class Meta:
managed = False
db_table = 'auth_user_user_permissions'
unique_together = (('user', 'permission'),)
class DjangoAdminLog(models.Model):
action_time = models.DateTimeField()
object_id = models.TextField(blank=True, null=True)
object_repr = models.CharField(max_length=200)
action_flag = models.PositiveSmallIntegerField()
change_message = models.TextField()
content_type = models.ForeignKey('DjangoContentType', models.DO_NOTHING, blank=True, null=True)
user = models.ForeignKey(AuthUser, models.DO_NOTHING)
class Meta:
managed = False
db_table = 'django_admin_log'
class DjangoContentType(models.Model):
app_label = models.CharField(max_length=100)
model = models.CharField(max_length=100)
class Meta:
managed = False
db_table = 'django_content_type'
unique_together = (('app_label', 'model'),)
class DjangoMigrations(models.Model):
app = models.CharField(max_length=255)
name = models.CharField(max_length=255)
applied = models.DateTimeField()
class Meta:
managed = False
db_table = 'django_migrations'
class DjangoSession(models.Model):
session_key = models.CharField(primary_key=True, max_length=40)
session_data = models.TextField()
expire_date = models.DateTimeField()
class Meta:
managed = False
db_table = 'django_session'
class TbArticle(models.Model):
id = models.IntegerField(primary_key=True)
title = models.CharField(max_length=255, blank=True, null=True)
content = models.CharField(max_length=255, blank=True, null=True)
publish_time = models.DateTimeField(blank=True, null=True)
update_time = models.DateTimeField(blank=True, null=True)
read_number = models.IntegerField(blank=True, null=True)
cat = models.ForeignKey('TbCat', models.DO_NOTHING, blank=True, null=True)
class Meta:
managed = False
db_table = 'tb_article'
class TbCat(models.Model):
id = models.IntegerField(primary_key=True)
cat_name = models.CharField(max_length=255, blank=True, null=True)
class Meta:
managed = False
db_table = 'tb_cat'
class TbReArticleComment(models.Model):
id = models.IntegerField(primary_key=True)
article = models.ForeignKey(TbArticle, models.DO_NOTHING, blank=True, null=True)
comment = models.CharField(max_length=255, blank=True, null=True)
email = models.CharField(max_length=255, blank=True, null=True)
blog_address = models.CharField(max_length=255, blank=True, null=True)
name = models.CharField(max_length=255, blank=True, null=True)
update_time = models.DateTimeField(blank=True, null=True)
class Meta:
managed = False
db_table = 'tb_re_article_comment'
class TbReArticleTags(models.Model):
id = models.IntegerField(primary_key=True)
article = models.ForeignKey(TbArticle, models.DO_NOTHING, blank=True, null=True)
tag = models.ForeignKey('TbTag', models.DO_NOTHING, blank=True, null=True)
class Meta:
managed = False
db_table = 'tb_re_article_tags'
class TbTag(models.Model):
id = models.IntegerField(primary_key=True)
tag_name = models.CharField(max_length=20, blank=True, null=True)
state = models.CharField(max_length=255, blank=True, null=True)
class Meta:
managed = False
db_table = 'tb_tag'
class TbUser(models.Model):
id = models.IntegerField(primary_key=True)
name = models.CharField(max_length=255, blank=True, null=True)
password = models.CharField(max_length=255, blank=True, null=True)
signature = models.CharField(max_length=255, blank=True, null=True)
login_id = models.CharField(max_length=20, blank=True, null=True)
class Meta:
managed = False
db_table = 'tb_user'
测试增删改查操作:
以save为例:
testDb.py代码
from django.http import HttpResponse
from Models.models import TbUser
# 数据库操作
def testdb(request):
user = TbUser()
user.name ="zhang"
user.login_id = "aaa@qq.com"
user.password = "1234567"
user.save()
return HttpResponse("<p>数据添加成功!</p>")
urls.py添加url拦截(相当于controller)
启动项目:python manage.py runserver 0.0.0.0:8080
浏览器输入url测试:
查看数据库,刷新
数据查询,很方便,
比如:查询id>10的所有user
数据库操作搞定!
有些时候出现新增的url拦截不起作用,需要手动重新启动一下!(一般是会自动更新的)
备注:主键自增:
id = models.AutoField(primary_key=True)
url传参数:注意这里是path了,不再是url
urlpatterns = [ # /hello url(r'hello', view.hello2), # / 匹配所有 但是是由最长匹配原则决定的 url(r'^$', view.hello), url(r'getUserList', view.hello3), # url(r'testDb', testDb.testdb), url(r'testDb2', testDb.testdb2), url(r'testDb3', testDb.testdb3), path('articles/<int:page>', view.hello1),#注意:<int:page>是将url中的articles/10
的10转为int存放到变量page中,对应的view.hello1方法应该是这样的,形参中有名为page的
]
效果:
官方示例:
urlpatterns = [
path('articles/2003/', views.special_case_2003),
path('articles/<int:year>/', views.year_archive),
path('articles/<int:year>/<int:month>/', views.month_archive),
path('articles/<int:year>/<int:month>/<slug:slug>/', views.article_detail),
]
Notes:
- To capture a value from the URL, use angle brackets.
- Captured values can optionally include a converter type. For example, use
<int:name>
to capture an integer parameter. If a converter isn’t included, any string, excluding a/
character, is matched. - There’s no need to add a leading slash, because every URL has that. For example, it’s
articles
, not/articles
.
Example requests:
- A request to
/articles/2005/03/
would match the third entry in the list. Django would call the functionviews.month_archive(request, year=2005, month=3)
. -
/articles/2003/
would match the first pattern in the list, not the second one, because the patterns are tested in order, and the first one is the first test to pass. Feel free to exploit the ordering to insert special cases like this. Here, Django would call the functionviews.special_case_2003(request)
-
/articles/2003
would not match any of these patterns, because each pattern requires that the URL end with a slash. -
/articles/2003/03/building-a-django-site/
would match the final pattern. Django would call the functionviews.article_detail(request, year=2003, month=3, slug="building-a-django-site")
获取表单提交信息:searchform.html
表单:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>搜索表单</title>
</head>
<body>
<body>
<form action="/articles/search" method="get">
<input type="text" name="q">
<input type="submit" value="搜索">
</form>
</body>
</body>
</html>
后台接收:search.pyfrom django.http import HttpResponse
from django.shortcuts import render_to_response
#搜索
# 跳转到搜索表单页面
def openSearchForm(request):
return render_to_response('searchform.html')
# 响应搜索请求
def searchArticleByTag(request):
request.encoding = 'utf-8'
if 'q' in request.GET:
message = '你搜索的内容为: ' + request.GET['q']
else:
message = '你提交了空表单'
print(message)
return HttpResponse(message)
urls.py配置:
url(r'^search-form$', search.openSearchForm),
path('articles/search', search.searchArticleByTag),
效果:
下一篇: 关于exec函数的返回值有关问题
推荐阅读
-
Python Django框架单元测试之文件上传测试示例
-
全面解读Python Web开发框架Django
-
Python ORM框架SQLAlchemy学习笔记之数据查询实例
-
python常用web框架简单性能测试结果分享(包含django、flask、bottle、tornado)
-
Python ORM框架SQLAlchemy学习笔记之数据添加和事务回滚介绍
-
Python ORM框架SQLAlchemy学习笔记之关系映射实例
-
Python ORM框架SQLAlchemy学习笔记之安装和简单查询实例
-
Python ORM框架SQLAlchemy学习笔记之映射类使用实例和Session会话介绍
-
Linux系统上Nginx+Python的web.py与Django框架环境
-
python web框架学习笔记