Django 学习总结(更新中)
1、常用命令
新建一个项目:django-admin.py startproject project-name 新建一个app:python manage.py startapp app-name 同步数据库:python manage.py syncdb,python manage.py makemigrations,python manage.py migrate 使用开发服务器:python manage.py runserver 清空数据库:python manage.py flush 创建超级管理员:python manage.py createsuperuser 导出数据导入数据:python manage.py dumpdata appname > appname.json,python manage.py loaddata appname.json django项目环境终端:python manage.py shell 数据库命令行:python manage.py dbshell
2、为django项目创建一个templates
在项目根目录mkdir templates 在setting.py中添加 'DIRS': [BASE_DIR+"/templates",],
3、创建一个app
python manage.py startapp appname
在mysql创建好相关数据库 create database db_name default character set utf8
setting.py中设置数据库的连接信息
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'test_db', 'USER': 'root', 'PASSWORD': '******', #密码 'HOST':'localhost', 'PORT':'3306', } }
并且在INSTALLED_APPS末尾中添加app的名称
设计好数据库表格(以后添加一个链接设计数据库)models.py
# models.py from django.db import models class Test(models.Model): name = models.CharField(max_length=20)
创建数据库表格
$ python manage.py migrate # 创建表结构 $ python manage.py makemigrations Model_name # 让 Django 知道我们在我们的模型有一些变更 $ python manage.py migrate Model_name # 创建表结构
4、绑定 URL 与视图函数
首先在 blog 应用的目录下创建一个 urls.py 文件
from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), ]
编写视图函数
from django.shortcuts import render, render_to_response from django.http import HttpResponse from .models import ...
def index(request):
return HttpResponse()# 直接的字符串或者文件
return render(request, 'cmd.html',context={})
return render_to_response()
修改总试图函数
urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^welcome/$', views.welcome), url(r'', include('TimeMng.urls', namespace='TimeMng')), ]
做了以上步骤后就可已在app下进行比较好的开发环境了
5、定制admin开发环境
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
from django.contrib import admin from .models import Zone, Department, Employee, Transation, Client class EmployeeAdmin(admin.ModelAdmin): list_display = ['epin', 'ename', 'esex', 'dname'] class ClientAdmin(admin.ModelAdmin): list_display = ['cnumber', 'cupk', 'calias', 'zone'] class DepartmentAdmin(admin.ModelAdmin): list_display = ['dname'] class ZoneAdmin(admin.ModelAdmin): list_display = ['zname'] class TransationAdmin(admin.ModelAdmin): list_display = ['index', 'pin', 'ename', 'time', 'state'] admin.site.register(Zone, ZoneAdmin) admin.site.register(Department, DepartmentAdmin) admin.site.register(Employee, EmployeeAdmin) admin.site.register(Transation, ) admin.site.register(Client, ClientAdmin)
暂时只有这些