Django入门

Django文档:

https://docs.djangoproject.com/en/1.10/ref/

一、简单创建app

1.1 命令行创建project和app。

django-admin startproject HelloWorld

cd HelloWorld

python manage.py startapp app01

1.2 pycharm创建app

 

2、将app01加入settings并配置url。

 

3、启动app

python manage.py runserver 8000

 

二、

生成环境:

settings.py

DEBUG = False

ALLOWED_HOSTS = ["*"]

2.1 配置加载html

 或者通过render()返回html页面。

def login(request):
    # content = open("templates/app01/login.html","r").read()
    # return HttpResponse(content)
    return render(request,"app01/login.html")

  

注意html里的加载的css,jq,js用http的方式或配置静态文件的方式引入。

 

2.2 django将表应用到数据库。

python manage.py makemigration   #根据class创建创建数据库的配置文件

python manage.py migrate       # 根据配置文件创建数据库表

 

2.3 django创建后台管理员账户

python manage.py createsuperuser

 

2.4 路由系统

动态路由,正则表达式: 这个(\d+) 会传入news(request,nid)函数。

 

二级路由

首先创建app01, python manage.py startapp app02

from django.conf.urls import url,include

,在app01目录下的urls.py下配置urls,在app02目录下的urls.py下配置urls

 

 

 2.5 数据库操作

数据库连接:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': 'day15',
        'HOST':'127.0.0.1',
        'PORT':'3306',
        'USER':'root',
        'PASSWORD':'root',
    }
}

  

modles.py

class UserInfo(models.Model):
    username = models.CharField(max_length=32)
    password = models.CharField(max_length=32)
    age = models.IntegerField()
# 默认会自动添加自增的id作为主键

一对多,多对多

class Author(models.Model):
    first_name = models.CharField(max_length=32)
    last_name = models.CharField(max_length=32)
    email = models.EmailField()

class Publisher(models.Model):
    name = models.CharField(max_length=64,unique=True)
    address = models.CharField(max_length=128)
    city = models.CharField(max_length=64)
    state_province = models.CharField(max_length=30)
    country = models.CharField(max_length=50)
    website = models.URLField()

class Book(models.Model):
    bookname = models.CharField(max_length=128)
    authors = models.ManyToManyField(Author)
    publisher = models.ForeignKey(Publisher)
    publish_date = models.DateField()

  

然后,执行python manage.py makemigrations ;  python manage.py migrate

E:\day15>python2 manage.py makemigrations
Migrations for 'app01':
  app01\migrations\0002_auto_20160807_2043.py:
    - Create model Author
    - Create model Book
    - Create model Publisher
    - Add field publisher to book
E:\day15>python2 manage.py migrate
Operations to perform:
  Apply all migrations: admin, app01, auth, contenttypes, sessions
Running migrations:
  Rendering model states... DONE
  Applying app01.0002_auto_20160807_2043... OK

会生成第三张表:

Django后台管理数据库。

首先在app01的admin.py下注册数据库表

import models
# Register your models here.
admin.site.register(models.UserInfo)
admin.site.register(models.Author)
admin.site.register(models.Book)
admin.site.register(models.Publisher)

创建后台用户:

 python manage.py createsuperuser

登录后台并操作表:

定制表在后台返回字符串:

class Author(models.Model):
    first_name = models.CharField(max_length=32)
    last_name = models.CharField(max_length=32)
    email = models.EmailField()
    def __unicode__(self):
        return "author: %s %s"%(self.first_name,self.last_name)

后台样式:

由于book是需要关联其他标的,所以在新增book数据时,关联字段是不能任意填写的,只能选择:

修改字段:

first_name = models.CharField(max_length=32,null=True)

python manage.py makemigrations,python manage.py migrate

虽然数据库种这个字段可以为空,但是在Gjango后台还是不能以空插入数据:

 

要以空值插入数据,需要修改类中的表定义:

first_name = models.CharField(max_length=32,null=True,blank=True)
"""
blank¶

Field.blank¶
If True, the field is allowed to be blank. Default is False.

Note that this is different than null. null is purely database-related, whereas 
blank is validation-related. If a field has blank=True, form validation will allow 
entry of an empty value. If a field has blank=False, the field will be required.
"""

参考文档:

https://docs.djangoproject.com/en/1.10/ref/models/fields/

 

增、删、改、查(针对userinfo表)

def db_h(request):
    # 增
    # models.UserInfo.objects.create(username="ds",password="123",age=18)
    # 删
    # models.UserInfo.objects.filter(username='ds').delete()
    # 改
    # models.UserInfo.objects.filter(age=18).update(age=20)
    # models.UserInfo.objects.all().update(age=19)
    # 查
    userlist_obj = models.UserInfo.objects.all()

    users = []
    for user in userlist_obj:
        users.append(user.username)

    userstring = json.dumps(users)
    # models.UserInfo.objects.filter(username='ds')
    # models.UserInfo.objects.filter(age=18).first()

    return HttpResponse(userstring)

  模糊查找:参见官方文档。

https://docs.djangoproject.com/en/1.10/ref/models/querysets/

https://docs.djangoproject.com/en/1.10/topics/db/queries/   

 

 对于上面的多对多手动新增书籍:

E:\python27\day15>python2 manage.py shell
>>> from datatime import datatime
>>> p = models.Publisher.object.filter().first()
>>> b =  models.Book(bookname="OWASP",publish_date=datetime.now(),publisher=p)
>>> b.save()
>>> a = models.Author.objects.filter().first()
>>> b.authors.add(a)
>>> b.authors.remove(a)

  

数据库取数据,并将数据传入html

# app01.views
def db_h(request):
    userlist_obj = models.UserInfo.objects.all()
    return render(request,"app01/tables.html",{"li":userlist_obj})

# templates.app01.tables.html
        <table>
            <tr>
                <th>姓名</th>
                <th>密码</th>
                <th>年龄</th>
            </tr>
            {% for item in li %}
            <tr>
                <td>{{ item.username}}</td>
                <td>{{ item.password }}</td>
                <td>{{ item.age }}</td>
            </tr>
            {% endfor %}
        </table>

  

2,6 引入静态文件

注意要是列表或元组,

 

 

 

 2.7 数据提交。

对于POST请求需在setttings里把跨站请求注释掉。# 'django.middleware.csrf.CsrfViewMiddleware',

我们可以通过POST和GET方式提交,提交到后台的数据通过request.GET或request.POST方式取得,request,method是提交的方法,值为"POST"或"GET"。

('val:', <QueryDict: {u'username': [u'gg'], u'age': [u'21'], u'password': [u'rr']}>)  , 这是在后台打印的POST方式的数据。我们可以通过request.POST["username"]获取username的值。

JSON数据转换:

# 将字典转为JSON格式(字符串)再发送给客户端
response_data_ok = {"status":"ok"}
return HttpResponse(json.dumps(response_data_ok))

# 客户端接收JSON格式的字符串后再反转为原来的格式
"success":function(msg1){
                            msg = JSON.parse(msg1)
}

  

 未完待续

 

 

2.8 Template渲染

基本语法:

E:\day15>python2 manage.py shell
Python 2.7.12 (v2.7.12:d33e0cf91556, Jun 27 2016, 15:19:22) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>>
>>> from django.template import Context,Template
>>> t = Template("My name is {{name}},I'am {{age}} years old")
>>> c = Context({"name":"DS","age":18})
>>> t.render(c)
u"My name is DS,I'am 18 years old"
>>> for i in [{"name":"DS","age":18},{"name":"lj","age":20}]:
...     print(t.render(Context(i)))
...
My name is DS,I'am 18 years old
My name is lj,I'am 20 years old
>>>

# 深度变量查找1
>>> p = {"name":"ow","age":20}
>>> t1 = Template("My name is {{person.name}}")
>>> c = Context({'person':p})
>>> t1.render(c)
u'My name is ow'


# 深度变量查找2
>>> t = Template("My name is {{item.1}}")
>>> c = Context({"item":["ds","lj","cc"]})
>>> t.render(c)
u'My name is lj'

# 深度查找3(类)
>>> import datetime
>>> d = datetime.date(2016,8,7)
>>> d.year
2016
>>> t = Template("today is {{i.year}} {{i.month}} {{i.day}}")
>>> c = Context({"i":d})
>>> t.render(c)
u'today is 2016 8 7'

Template用于模板文件语法:

{% for item in li %}
            <tr>
                <td>{{ item.username}}</td>
                <td>{{ item.password }}</td>
                <td>{{ item.age }}</td>
            </tr>
{% endfor %}

forloop.counter0 循环计数器
value}divisibleby:"2"  能被2整除

html继承和重写

模板app01/modle.html

<html>
<body>
<div>...</div>
{% block content %}
{% endblock %}
</body>
</html>

继承和重写app01/admin.html

{%  extends "app01/modle.html" %}

{% block content %}
    <div class="container">
        <table class="table table-bordered table-hover ">
            <tr>
                <th>姓名</th>
                <th>密码</th>
                <th>年龄</th>
            </tr>
            {% for item in li %}
            <tr>
                <td>{{ item.username}}</td>
                <td>{{ item.password }}</td>
                <td>{{ item.age }}</td>
            </tr>
            {% endfor %}
        </table>
    </div>
{%  endblock %}

导入

# weather.html
<div>
Weather
</div>

# login.html
{% include "app01/weather.html %}

  

 

posted @ 2016-08-06 14:41  电神  阅读(304)  评论(0编辑  收藏  举报