Django回忆录
Django使用回忆:
1、安装django:
pip install django==1.9
2、创建项目及应用:
django-admin startproject web
django-admin startap blog
3、配置数据库、二级url:
web/setting.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog', ] ... DATABASES = { 'default': { # 'ENGINE': 'django.db.backends.sqlite3', # 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), 'ENGINE': 'django.db.backends.mysql', 'NAME':'test_blog', 'USER':'ahaii', 'PASSWORD':'123456', 'HOST':'', 'PORT':'', } }
web/urls.py: urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^blog/', include('blog.urls')), ]
blog/urls.py: from blog import views urlpatterns = [ url(r'^$', views.index), ]
blog/views.py: from django.shortcuts import render,HttpResponse # Create your views here. def index(request): return HttpResponse('Hello Django')
4、创建数据库模型:
blog/models.py: from django.db import models # Create your models here. class Article(models.Model): title = models.CharField(max_length=100) category = models.CharField(max_length=50,blank=True) date_time = models.DateTimeField(auto_now_add=True) content = models.TextField(blank=True,null=True) def __unicode__(self): return self.title class Meta: ordering = ['-date_time']
5、同步数据库:
python manage.py makemigrations
python manage.py migrate
其中,makemigrations是扫描变动后在本地的app目录下的migrations包里生成迁移用的代码,但是并不会执行。migrate则是根据migrations包下的代码操作数据库,但并不检查models的修改变动。所以更改models后应先makemigrations然后migrate。
6、创建超级用户:
python manage.py createsuperuser
7、利用python shell交互模式操作数据库:
python manage.py shell >>>from blog.models import Article >>>Article.objects.create(title='...',category='...',content='...')//插入数据 >>>Article.objects.all()//查询所有记录,返回列表 >>>Article.objects.get(id=1)//查询第一条
>>>a=Article.objects.get(title='Car')
>>>a.content='The traffice is so busy!'//修改内容
>>>>a.save()//写入数据库
8、动态url:(获取url中的参数)
blog/views.py:
def detail(request,args):
post = Article.objects.all()[int(args)] //默认输入为字符串,转换为整型,列表索引
str = ('title=%s,category=%s,content=%s') %(post.title,post.category,post.content)
return HttpResponse(str)
blog/urls.py: urlpatterns = [ url(r'^$', views.index), url(r'(?P<args>\d+)/$',views.detail)// \w+可匹配数字和字母 ]
9、使用模版:
web项目下创建templates/test.html,设置模版路径:
web/setting: 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', ], }, }, ]
templates/test.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Just for test template</title> <style> body{ background-color: red; } strong{ color:lightseagreen; } </style> </head> <body> <h1>Hello Django</h1> <strong>{{ time }}</strong> </body> </html>
blog/views:
from datetime import datetime def template(request): return render(request,'test.html',{'time':datetime.now()})
blog/urls: urlpatterns = [ url(r'template/$',views.template) ]
以上目录结构:
web-| |-blog |-manage.py |-templates |-web
话说Django数据库操作中get和filter的区别:
1、get:从数据库中找到匹配的一条,返回一个满足查询条件的对象。若没有查到符合条件的数据,会发生错误。
2、filter:从数据库中找到匹配的一条,返回一个满足查询条件的列表。若没有查到符合条件的数据,会返回一个口列表[]。