欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Django在視圖中使用表單并和數(shù)據(jù)庫(kù)進(jìn)行數(shù)據(jù)交互的實(shí)現(xiàn)

 更新時(shí)間:2022年07月26日 11:24:23   作者:黃鋼  
本文主要介紹了Django在視圖中使用表單并和數(shù)據(jù)庫(kù)進(jìn)行數(shù)據(jù)交互,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧

寫(xiě)在前面

博主近期有時(shí)間的話(huà),一直在抽空看Django相關(guān)的項(xiàng)目,苦于沒(méi)有web開(kāi)發(fā)基礎(chǔ),對(duì)JavaScript也不熟悉,一直在從入門(mén)到放棄的邊緣徘徊(其實(shí)已經(jīng)放棄過(guò)幾次了,如下圖,一年前的筆記)??傮w感受web開(kāi)發(fā)要比其他技術(shù)棧難,前后端技術(shù)都有涉及。如果沒(méi)有實(shí)體項(xiàng)目支撐的話(huà),很難學(xué)下去。但不管怎樣,學(xué)習(xí)都是一件痛苦的事情,堅(jiān)持下去總會(huì)有收獲。

在這里插入圖片描述

本博客記錄的是《Django web 應(yīng)用開(kāi)發(fā)實(shí)戰(zhàn)》這本書(shū)第八章表單與模型中的相關(guān)內(nèi)容,主要內(nèi)容是表單與數(shù)據(jù)庫(kù)的交互。編譯環(huán)境如下:

  • Python3.7
  • pycharm2020.1專(zhuān)業(yè)版(社區(qū)版應(yīng)該是不支持Django項(xiàng)目調(diào)試的) 項(xiàng)

目結(jié)構(gòu)及代碼

項(xiàng)目結(jié)構(gòu)

在pycharm中建立Django項(xiàng)目后,會(huì)自動(dòng)生成一些基礎(chǔ)的文件,如settings.py,urls.py等等,這些基礎(chǔ)的東西,不再記錄,直接上我的項(xiàng)目結(jié)構(gòu)圖。

在這里插入圖片描述

上圖中左側(cè)為項(xiàng)目結(jié)構(gòu),1為項(xiàng)目應(yīng)用,也叫APP,2是Django的項(xiàng)目設(shè)置,3是項(xiàng)目的模板,主要是放網(wǎng)頁(yè)的。

路由設(shè)置

路由設(shè)置是Django項(xiàng)目必須的,在新建項(xiàng)目是,在index目錄、MyDjango目錄下面生成了urls.py文件,里面默認(rèn)有項(xiàng)目的路由地址,可以根據(jù)項(xiàng)目情況更改,我這里上一下我的路由設(shè)置。

# MyDjango/urls.py
"""MyDjango URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/3.0/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include(('index.urls', 'index'), namespace='index'))
]


# index/urls.py
#!/usr/bin/env python
#-*- coding:utf-8 -*-
# author:HP
# datetime:2021/6/15 15:35
from django.urls import path, re_path
from .views import *
urlpatterns = [
    path('', index, name='index'),
]

數(shù)據(jù)庫(kù)配置

數(shù)據(jù)庫(kù)的配置,以及模板的設(shè)置等內(nèi)容都在settings.py文件中,在項(xiàng)目生成的時(shí)候,自動(dòng)生成。
數(shù)據(jù)庫(kù)設(shè)置在DATABASE字典中進(jìn)行設(shè)置,默認(rèn)的是sqlite3,我也沒(méi)改。這里可以同時(shí)配置多個(gè)數(shù)據(jù)庫(kù),具體不再記錄。
看代碼:

"""
Django settings for MyDjango project.

Generated by 'django-admin startproject' using Django 3.0.8.

For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '6##c(097i%=eyr-uy!&m7yk)+ar+_ayjghl(p#&(xb%$u6*32s'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    # add a new app index
    'index',
    'mydefined'
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'MyDjango.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')]
        ,
        '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',
            ],
        },
    },

]
'''
    {
        'BACKEND': 'django.template.backends.jinja2.Jinja2',
        'DIRS': [
            os.path.join(BASE_DIR, 'templates'),
        ],
        'APP_DIRS': True,
        'OPTIONS': {
            'environment': 'MyDjango.jinja2.environment'
        },
    },
    '''

WSGI_APPLICATION = 'MyDjango.wsgi.application'


# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}


# Password validation
# https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/3.0/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/

STATIC_URL = '/static/'

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static')
]

定義模型

怎么來(lái)解釋“模型”這個(gè)東西,我感覺(jué)挺難解釋清楚,首先得解釋ORM框架,它是一種程序技術(shù),用來(lái)實(shí)現(xiàn)面向?qū)ο缶幊陶Z(yǔ)言中不同類(lèi)型系統(tǒng)的數(shù)據(jù)之間的轉(zhuǎn)換。這篇博客涉及到前端和后端的數(shù)據(jù)交互,那么首先你得有個(gè)數(shù)據(jù)表,數(shù)據(jù)表是通過(guò)模型來(lái)創(chuàng)建的。怎么創(chuàng)建呢,就是在項(xiàng)目應(yīng)用里面創(chuàng)建models.py這個(gè)文件,然后在這個(gè)文件中寫(xiě)幾個(gè)類(lèi),用這個(gè)類(lèi)來(lái)生成數(shù)據(jù)表,先看看這個(gè)項(xiàng)目的models.py代碼。

from django.db import models


class PersonInfo(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=20)
    age = models.IntegerField()
    # hireDate = models.DateField()

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = '人員信息'


class Vocation(models.Model):
    id = models.AutoField(primary_key=True)
    job = models.CharField(max_length=20)
    title = models.CharField(max_length=20)
    payment = models.IntegerField(null=True, blank=True)
    person = models.ForeignKey(PersonInfo, on_delete=models.CASCADE)

    def __str__(self):
        return str(self.id)

    class Meta:
        verbose_name = '職業(yè)信息'



簡(jiǎn)單解釋一下,這段代碼中定義了兩個(gè)類(lèi),一個(gè)是PersonInfo,一個(gè)是Vocation,也就是人員和職業(yè),這兩個(gè)表通過(guò)外鍵連接,也就是說(shuō),我的數(shù)據(jù)庫(kù)中,主要的數(shù)據(jù)就是這兩個(gè)數(shù)據(jù)表。
在創(chuàng)建模型后,在終端輸入以下兩行代碼:

python manage.py makemigrations
python manage.py migrate

這樣就可以完成數(shù)據(jù)表的創(chuàng)建,數(shù)據(jù)遷移也是這兩行代碼。同時(shí),還會(huì)在項(xiàng)目應(yīng)用下生成一個(gè)migrations文件夾,記錄你的各種數(shù)據(jù)遷移指令。
看看生成的數(shù)據(jù)庫(kù)表:

在這里插入圖片描述

上面圖中,生成了personinfo和vocation兩張表,可以自行在表中添加數(shù)據(jù)。

定義表單

表單是個(gè)啥玩意兒,我不想解釋?zhuān)驗(yàn)槲易约阂彩且恢虢狻_@個(gè)就是你的前端界面要顯示的東西,通過(guò)這個(gè)表單,可以在瀏覽器上生成網(wǎng)頁(yè)表單。怎么創(chuàng)建呢,同樣是在index目錄(項(xiàng)目應(yīng)用)下新建一個(gè)form.py文件,在該文件中添加以下代碼:

#!/usr/bin/env python
#-*- coding:utf-8 -*-
# author:HP
# datetime:2021/6/24 14:55

from django import forms
from .models import *
from django.core.exceptions import ValidationError


def payment_validate(value):
    if value > 30000:
        raise ValidationError('請(qǐng)輸入合理的薪資')


class VocationForm(forms.Form):
    job = forms.CharField(max_length=20, label='職位')
    title = forms.CharField(max_length=20, label='職稱(chēng)',
                            widget=forms.widgets.TextInput(attrs={'class': 'cl'}),
                            error_messages={'required': '職稱(chēng)不能為空'})
    payment = forms.IntegerField(label='薪資',
                                 validators=[payment_validate])

    value = PersonInfo.objects.values('name')
    choices = [(i+1, v['name']) for i, v in enumerate(value)]
    person = forms.ChoiceField(choices=choices, label='姓名')

    def clean_title(self):
        data = self.cleaned_data['title']
        return '初級(jí)' + data

簡(jiǎn)單解釋一下,就是說(shuō)我待會(huì)兒生成的網(wǎng)頁(yè)上,要顯示job、title、payment還有一個(gè)人名下拉框,這些字段以表單形式呈現(xiàn)在網(wǎng)頁(yè)上。

修改模板

模板實(shí)際上就是網(wǎng)頁(yè)上要顯示的信息,為啥叫模板呢,因?yàn)槟憧梢宰远x修改,在index.html中修改,如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
{% if v.errors %}
    <p>
        數(shù)據(jù)出錯(cuò)了,錯(cuò)誤信息:{{ v.errors }}
    </p>
{% else %}
    <form action="" method="post">
        {% csrf_token %}
        <table>
            {{ v.as_table }}
        </table>
        <input type="submit" value="submit">
    </form>
{% endif %}
</body>
</html>

視圖函數(shù)

視圖函數(shù)其實(shí)就是views.py文件中的函數(shù),這個(gè)函數(shù)非常重要,在項(xiàng)目創(chuàng)建的時(shí)候自動(dòng)生成,它是你的前后端連接的樞紐,不管是FBV視圖還是CBV視圖,都需要它。
先來(lái)看看這個(gè)項(xiàng)目中視圖函數(shù)的代碼:

from django.shortcuts import render
from django.http import HttpResponse
from index.form import VocationForm
from .models import *


def index(request):
    # GET請(qǐng)求
    if request.method == 'GET':
        id = request.GET.get('id', '')
        if id:
            d = Vocation.objects.filter(id=id).values()
            d = list(d)[0]
            d['person'] = d['person_id']
            i = dict(initial=d, label_suffix='*', prefix='vv')
            # 將參數(shù)i傳入表單VocationForm執(zhí)行實(shí)例化
            v = VocationForm(**i)
        else:
            v = VocationForm(prefix='vv')
        return render(request, 'index.html', locals())
    # POST請(qǐng)求
    else:
        # 由于在GET請(qǐng)求設(shè)置了參數(shù)prefix
        # 實(shí)例化時(shí)必須設(shè)置參數(shù)prefix,否則無(wú)法獲取POST的數(shù)據(jù)
        v = VocationForm(data=request.POST, prefix='vv')
        if v.is_valid():
            # 獲取網(wǎng)頁(yè)控件name的數(shù)據(jù)
            # 方法一
            title = v['title']
            # 方法二
            # cleaned_data將控件name的數(shù)據(jù)進(jìn)行清洗
            ctitle = v.cleaned_data['title']
            print(ctitle)
            # 將數(shù)據(jù)更新到模型Vocation
            id = request.GET.get('id', '')
            d = v.cleaned_data
            d['person_id'] = int(d['person'])
            Vocation.objects.filter(id=id).update(**d)
            return HttpResponse('提交成功')
        else:
            # 獲取錯(cuò)誤信息,并以json格式輸出
            error_msg = v.errors.as_json()
            print(error_msg)
            return render(request, 'index.html', locals())

其實(shí)就一個(gè)index函數(shù),不同請(qǐng)求方式的時(shí)候,顯示不同的內(nèi)容。這里要區(qū)分get和post請(qǐng)求,get是向特定資源發(fā)出請(qǐng)求,也就是輸入網(wǎng)址訪問(wèn)網(wǎng)頁(yè),post是向指定資源提交數(shù)據(jù)處理請(qǐng)求,比如提交表單,上傳文件這些。
好吧,這樣就已經(jīng)完成了項(xiàng)目所有的配置。
啟動(dòng)項(xiàng)目,并在瀏覽器中輸入以下地址:http://127.0.0.1:8000/?id=1

這是個(gè)get請(qǐng)求,顯示內(nèi)容如下:

在這里插入圖片描述

這個(gè)網(wǎng)頁(yè)顯示了form中設(shè)置的表單,并填入了id為1的數(shù)據(jù)信息。
我想修改這條數(shù)據(jù)信息,直接在相應(yīng)的地方進(jìn)行修改,修改如下:

在這里插入圖片描述

然后點(diǎn)擊submit按鈕,也就是post請(qǐng)求,跳轉(zhuǎn)網(wǎng)頁(yè),顯示如下:

在這里插入圖片描述

刷新俺們的數(shù)據(jù)庫(kù),看看數(shù)據(jù)變化了沒(méi):

在這里插入圖片描述

id為1的數(shù)據(jù)已經(jīng)修改成了我們?cè)O(shè)置的內(nèi)容。
至此,表單和數(shù)據(jù)交互這個(gè)小節(jié)的內(nèi)容已經(jīng)結(jié)束。

記錄感受

Django項(xiàng)目,創(chuàng)建之初要設(shè)置路由,如果要用到數(shù)據(jù)庫(kù),需要配置數(shù)據(jù)庫(kù),然后通過(guò)模型來(lái)創(chuàng)建數(shù)據(jù)表,并通過(guò)終端指令完成數(shù)據(jù)表創(chuàng)建和遷移,隨后定義表單格式,最后在視圖函數(shù)中設(shè)置各種請(qǐng)求方式。
感受就是兩個(gè)字,繁雜、

到此這篇關(guān)于Django在視圖中使用表單并和數(shù)據(jù)庫(kù)進(jìn)行數(shù)據(jù)交互的實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)Django 數(shù)據(jù)交互內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論