django的使用

1.新建project

django-admin.py startproject frist
 python manage.py runserver 0.0.0.0:8000

2.实现C与V的交互

(1)vim urls.py
          from views import fristfunc
          url(r'^frist/', fristfunc),
 (2)vim views.py
      from django.http import HttpResponse
          def fristfunc(requst):

returnHttpResponse('iamagirl')

3.在views中引入模板template

(1)在与manage.py同级mkdirfristtem

(2)fristtem->1.html

   (3)
vim 1.html
      <html>
      <head>
      </head>
      <body>
      <h1>{{canshu}}</h1>
      </body>
      </html>

(4)vimsetting.py

添加TEMPLATE_DIRS=('/home/..../',)注释:引号内为1.html的路径.实现M与数据库的交互

4.新建app

    
python manage.py startapp fristapp
     vim models.py(定义表的字段)
      from django.db import models
      # Create your models here.
      class Publisher(models.Model):
      name=models.CharField(max_length=30)
      xingbie=models.CharField(max_length=30)
      def __unicode__(self):
          return self.name
更改配置文件:setting.py
  DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql', 
        'NAME': 'books',    #你的数据库名称
        'USER': 'root',   #你的数据库用户名
        'PASSWORD': '', #你的数据库密码
        'HOST': '', #你的数据库主机,留空默认为localhost
        'PORT': '3306', #你的数据库端口
    }
}

注:要在数据库里建相应的book数据库

python manage.py validate  //验证table是否有格式错误
python manage.py makemigrations myapp
python manage.py migrate/syncdb//(同步数据库,centos7用migrate)

5.在命令行往数据库里加入数据

 
python manage.py shell
   from fristmysql.models import Publisher
   p1=Publisher(name="",xingbie="")
   p1.save()
   publisher_list=Publisher.objects.all()
   publisher_list

6.Django站点管理

 
vim admin.py
    from django.contrib import admin
admin.autodiscover()
 (r'^admin/', admin.site.urls),

建djano_site表,同步数据库

    
# Register your models here.
       from django.contrib import admin
       from fristapp.models import Publisher
       admin.site.register(Publisher)

注:python对象转化为字典views.py加入下行

json.dumps(mm, default = lambda o: o.__dict__)   mm为Python对象
或者:
def toJSON(self):
        return json.dumps(dict([(attr, getattr(self, attr)) for attr in [f.name for f in self._meta.fields]]))
row=models.ChatUsers.objects.get(name='Carlos  Flowers')

def fristfunc(requst):
    return HttpResponse(toJSON(row))

相关推荐