Django框架學習

<<寫在前面:

    本篇博客爲鄙人學習python的django框架所做的筆記,因爲第一次寫這個東西,所以有很多地方需要注意的,所以在這裏把所有需要自己修改設置的地方都寫出來了,作爲自己的學習經歷,也希望能給大家一點提示。裏面包含了一些基本操作,註釋的部分爲另一種操作或方法。#^_^#

注:綠色部分爲工程下的文件名,淺藍色的爲該文件中需要增加或修改的部分代碼,沒列出來的目前應該是初級階段不用修改的了

__init__.py:

import pymysql

pymysql.install_as_MySQLdb()

setting.py:

INSTALLED_APPS = [...]     #這裏加上你的應用名

DATABASES = {     #根據需要修改所用的數據庫
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'webdb',
        'USER': 'root',
        'PASSWORD': '123456',
        'HOST': 'localhost',
        'PORT': '3306',
    }

}

TEMPLATES = [    #視圖對應的模板,需先在工程文件夾下建立templates文件夾(存放.html文件)
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        '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',
            ],
        },
    },
]

LANGUAGE_CODE = 'zh-Hans'    #所用文字編碼

STATIC_URL = '/static/'    #在工程下建立static文件夾後加上這兩句話

STATICFILES_DIRS = (BASE_DIR,'static')

urls.py:

from django.conf.urls import url,include
from django.contrib import admin
from index import views as v
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^$',v.index_views),
]
urlpatterns +=[
    url(r'^login/',v.login_views),
]
urlpatterns +=[
    url(r'^register/',v.register_views),
]
urlpatterns +=[
    url(r'^01_author_add/$',v.author_add_views),
    url(r'^02_query/$',v.query_views),
    url(r'^03_update/(\d+)$',v.update_views,name='update'),
    url(r'^04_del/(\d+)/$',v.del_views,name='del'),#(\d+)表示傳一個參數,'del'表示視圖別名
]
urlpatterns +=[
    url(r'^06_oto/$',v.oto_views),
    url(r'^07_request',v.request_views),
]

admin.py:  #後臺管理

# -*- coding: UTF-8 -*-
from django.contrib import admin
from .models import *
# Register your models here.

#admin.site.register(Author)

class  AuthorAdmin(admin.ModelAdmin):
    list_display = ['name','age','email']#指定顯示在實體信息頁面上的信息
    list_display_links = ['name','email']#鏈接到詳細頁面
    list_editable = ['age']#設置display中可修改的屬性,但不能修改上面link中的屬性對應的值
    search_fields = ['name','email']#指定允許被搜索的字段
    list_filter = ['age']
    #fields = ('email','name','age')#分塊顯示
    fieldsets = (
        ('基本設置',{
                'fields':('name','age')
            }),
        ('高級設置',{
                'fields':('email',),
                #摺疊效果
                'classes':('collapse',)
            }),
        )
admin.site.register(Author,AuthorAdmin)
class PublisherAdmin(admin.ModelAdmin):
    list_display = ['name','address','city']
    list_editable = ['address','city']
    search_fields = ['address','city']
    fieldsets = (
        ('基本設置',{
                'fields':('name','address','city')
            }),
        ('高級設置',{
                'fields':('country','website'),
                #摺疊效果
                'classes':('collapse',)
            }),
        )
admin.site.register(Publisher,PublisherAdmin)
class WifeAdmin(admin.ModelAdmin):
    list_display = ['name','age','author']
admin.site.register(Wife,WifeAdmin)

models.py:

# -*- coding: UTF-8 -*-
from django.db import models

# Create your models here.

class Publisher(models.Model):
    name = models.CharField(max_length=30)
    address = models.CharField(max_length=50)
    city = models.CharField(max_length=30)
    country = models.CharField(max_length=30)
    website = models.URLField()
    def __str__(self):
        return self.name
    class Meta:#內部類
        #db_table = 'author'#修改表名
        verbose_name = '推送者'#定義類在admin中的顯示
        verbose_name_plural = verbose_name


class Author(models.Model):
    name = models.CharField(max_length=30)
    age = models.IntegerField()
    email = models.EmailField()
    def __str__(self):
        return self.name
    class Meta:#內部類
        #db_table = 'author'#修改表名
        verbose_name = '作者'#定義類在admin中的顯示
        verbose_name_plural = verbose_name
        ordering = ["-age"]#按年齡降序排序

class Book(models.Model):
    title = models.CharField(max_length=50)
    publication_date = models.DateField()
class Models(models.Model):

    isActiveUser = models.BooleanField()

class Wife(models.Model):
    name = models.CharField(max_length=30)
    age = models.IntegerField()
    author = models.OneToOneField(Author,null=True)
    def __str__(self):
        return self.name
    class Meta:
        db_table = "wife"
        verbose_name = '老婆'

        verbose_name_plural = verbose_name

class Good(models.Model):
    title = models.CharField(max_length=30,verbose_name='商品名稱')
    price = models.DecimalField(max_digits=7,decimal_places=2,verbose_name='商品價格')
    spec = models.CharField(max_length=30,verbose_name='商品規格')
    picture = models.ImageField(upload_to='static/upload/goods',verbose_name='商品圖片')

    isActive = models.BooleanField(default=True,verbose_name='在售')

class GoodsType(models.Model):
    title = models.CharField(max_length=30,verbose_name='類別名稱')
    desc = models.TextField(null=True,verbose_name='類別描述')

    picture = models.ImageField(upload_to='static/upload/goodsType',verbose_name='類別圖片')

views.py:

# -*- coding: UTF-8 -*-  
from django.shortcuts import render
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from .models import *
from django.db.models import F,Q

# Create your views here.

def index_views(request):
    #request.scheme請求協議
    #request.body請求主體
    #request.path請求路徑
    #request.get_host()請求主機/域名
    #request.method請求方式
    #request.GET封裝了GET方式的請求數據
    #request.POST
    #request.COOKIES
    #request.META

    return HttpResponse('main')

def login_views(request):
    if request.method=='GET':
        return render(request,'login.html')
    else:
        uphone = request.POST.get('uphone')
        upwd = request.POST.get('upwd')
        return HttpResponse(uphone+':'+upwd)

def register_views(request):
    return render(request,'register.html')

def author_add_views(request):
    #way1
    Author.objects.create(name='zzg',age=21,email='[email protected]')
    Author.objects.create(name='hhh',age=32,email='[email protected]')

    return HttpResponse("增加數據成功")

def query_views(request):
    listAuthor = Author.objects.all()
    #listAuthor = Author.objects.values('name','age')   #查詢這兩個字段的數據集
    #listAuthor = Author.objects.all().order_by('-id')  #降序排返回數據集
    #listAuthor = Author.objects.exclude(id=2)          #查尋id != 2的數據集
    #listAuthor = Author.objects.filter(id=2)           #查詢id == 2的數據集
    #Author = Author.objects.get(id=2)                  #查詢id == 2的單條數據print(Author.name)
    #listAuthor = Author.objects.filter(age__gt=33)     #查詢age>33 的數據集,__gte表示大於等於
    #listAuthor = Author.objects.filter(name__contains='寶') #查詢name屬性中包含'寶'字的數據集
    #listAuthor = Author.objects.filter(name__startwith='張')#查詢name屬性中以'張'字開頭的數據集
    #listAuthor = Author.objects.filter(name__endwith='豐')
    #listAuthor = Author.objects.filter(Q(id=1) | Q(age=31)) #查詢id爲1或者age爲31的數據集

    return render(request,'02_query.html',locals())     #locals把函數中所有變量傳入.html中

def update_views(request,id):
    if request.method == 'GET':
        author = Author.objects.get(id=id)
        return render(request,'update.html',locals())
    else:
        author = Author.objects.get(id=id)
        print(author)
        author.name = request.POST.get('name')
        author.age = request.POST.get('age')
        author.email = request.POST.get('email')
        author.save()
        return HttpResponseRedirect('/02_query')
    #單個修改
    #author = Author.objects.get(id=id)
    #author.name = '張三'
    #author.age = 56
    #author.save()
    #批量修改
    #Author.objects.filter(age__gt=50).update(age=60)
    #Author.objects.all().update(age = F('age')+10)#F獲取某列的值

    return query_views(request)

def del_views(request,id):#刪除操作,id爲傳入參數
    Author.objects.get(id=id).delete()
    return query_views(request) #視圖轉發
    #return HttpResponseRedirect('/02_query')#視圖重定向

def oto_views(request):
    #正向查詢
    # title = "通過wife找author"
    # w = Wife.objects.get(id=1)
    # a = w.author
    #反向查詢
    title = "通過author找wife"
    a = Author.objects.get(id=11)
    w = a.wife
    return render(request,'oto.html',locals())

def request_views(request):
    #print(dir(request))
    scheme = request.scheme
    body = request.body
    path = request.path
    method = request.method
    host = request.get_host()
    get = request.GET
    post = request.POST
    cookies = request.COOKIES
    meta = request.META

    return render(request,'request.html',locals())

02_query.html:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Table</title>
</head>
<body>
    <table>
        <thead>
            <tr>
                <th>ID</th>
                <th>姓名</th>
                <th>年齡</th>
                <th>郵箱</th>
                <th>操作</th>
            </tr>
        </thead>
        <tbody>
            {%for au in listAuthor%}
            <tr>
                <td>{{au.id}}</td>
                <td>{{au.name}}</td>
                <td>{{au.age}}</td>
                <td>{{au.email}}</td>
                <td>
                <a href="{%url 'del' au.id%}">刪除</a>
                <a href="{%url 'update' au.id%}">修改</a>
                </td>
            </tr>
            {%endfor%}
        </tbody>
    </table>

</body>

login.html:

{%load static%}
<!doctype html>
<html lang="en">
 <head>
  <meta charset="UTF-8">
  <title>會員登錄</title>
<!-- <link rel="stylesheet" href="/static/css/login.css"> -->
  <link rel="stylesheet" href="{%static 'css/login.css'%}">
 </head>
 <body>
  <div id="container">
<h2 class="title">會員登錄</h2>
<!-- 下 左 :圖片 -->
<p>
<img src="/static/images/huiyuan.jpg">
<a href="http://127.0.0.1:8000/register/">會員註冊&gt;</a>
</p>
<!-- 下 右 :登錄form -->
<div id="login">
<form action="login" method="post">
<!--解決post的跨站點攻擊403-->
    {%csrf_token%}
<!-- 第一行:手機號 -->
<div class="form-line">
<p>手機號</p>
<div>
<input type="text" name="uphone" class="form-control">
</div>
</div>
<!-- 第二行:密碼 -->
<div class="form-line">
<p>密碼</p>
<div>
<input type="password" name="upwd" class="form-control">
</div>
</div>

<!-- 第三行:記住密碼 -->
<div class="form-line">
<p></p>
<div>
<p>
<a href="#">忘記密碼</a>
<a href="#">快捷登錄</a>
</p>
<input type="checkbox" name="isSaved" class="isSaved" id="isSaved">
<label for="isSaved">記住密碼</label>
</div>
</div>
<!-- 第四行:登錄 & 註冊會員 -->
<div class="form-line">
<p></p>
<div>
<a href="http://127.0.0.1:8000/register/" class="register">註冊會員</a>
<input type="submit" value="登錄" class="btnLogin">
</div>
</div>
</form>
</div>
</div>
 </body>

</html>

request.html:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Table</title>
</head>
<body>
    <div style="color:purple">
    <h2 align="center">{{title}}</h2>
    <h3 align="center">scheme:{{scheme}}</h3>
    <p align="center"> body:{{body}}</p>
    <p align="center"> path:{{path}}<p>
    <p align="center"> method:{{method}}</p>
    <p align="center"> host:{{host}}</p>
    <p align="center"> get:{{get}}</p>
    <p align="center"> post:{{post}}</p>
    <p align="center"> cookies:{{cookies}}</p>
    <p align="center"> meta:{{meta}}</p>
    </div>
</body>

</html>

update.html:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Table</title>
</head>
<body>
    <form action="{% url 'update' author.id %}" method='post'>
    {%csrf_token%}
    NAME<input type='text' name='name' value="{{author.name}}">
    AGE<input type='text' name='age' value="{{author.age}}">
    EMAIL<input type='text' name='email' value="{{author.email}}">
    <input type='submit' value='update'>
    </form>
</body>
</html>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章