Django入門

Django文檔:css

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

1、簡單建立apppython

1.1 命令行建立project和app。web

django-admin startproject HelloWorld正則表達式

cd HelloWorldsql

python manage.py startapp app01shell

1.2 pycharm建立app數據庫

 

二、將app01加入settings並配置url。django

 

三、啓動appjson

python manage.py runserver 8000

 

2、

生成環境:

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 %}
相關文章
相關標籤/搜索