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

本博客記錄的是《Django web 應(yīng)用開發(fā)實戰(zhàn)》這本書第八章表單與模型中的相關(guān)內(nèi)容,主要內(nèi)容是表單與數(shù)據(jù)庫的交互。編譯環(huán)境如下:
- Python3.7
- pycharm2020.1專業(yè)版(社區(qū)版應(yīng)該是不支持Django項目調(diào)試的) 項
目結(jié)構(gòu)及代碼
項目結(jié)構(gòu)
在pycharm中建立Django項目后,會自動生成一些基礎(chǔ)的文件,如settings.py,urls.py等等,這些基礎(chǔ)的東西,不再記錄,直接上我的項目結(jié)構(gòu)圖。

上圖中左側(cè)為項目結(jié)構(gòu),1為項目應(yīng)用,也叫APP,2是Django的項目設(shè)置,3是項目的模板,主要是放網(wǎng)頁的。
路由設(shè)置
路由設(shè)置是Django項目必須的,在新建項目是,在index目錄、MyDjango目錄下面生成了urls.py文件,里面默認(rèn)有項目的路由地址,可以根據(jù)項目情況更改,我這里上一下我的路由設(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ù)庫配置
數(shù)據(jù)庫的配置,以及模板的設(shè)置等內(nèi)容都在settings.py文件中,在項目生成的時候,自動生成。
數(shù)據(jù)庫設(shè)置在DATABASE字典中進(jìn)行設(shè)置,默認(rèn)的是sqlite3,我也沒改。這里可以同時配置多個數(shù)據(jù)庫,具體不再記錄。
看代碼:
"""
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')
]
定義模型
怎么來解釋“模型”這個東西,我感覺挺難解釋清楚,首先得解釋ORM框架,它是一種程序技術(shù),用來實現(xiàn)面向?qū)ο缶幊陶Z言中不同類型系統(tǒng)的數(shù)據(jù)之間的轉(zhuǎn)換。這篇博客涉及到前端和后端的數(shù)據(jù)交互,那么首先你得有個數(shù)據(jù)表,數(shù)據(jù)表是通過模型來創(chuàng)建的。怎么創(chuàng)建呢,就是在項目應(yīng)用里面創(chuàng)建models.py這個文件,然后在這個文件中寫幾個類,用這個類來生成數(shù)據(jù)表,先看看這個項目的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è)信息'
簡單解釋一下,這段代碼中定義了兩個類,一個是PersonInfo,一個是Vocation,也就是人員和職業(yè),這兩個表通過外鍵連接,也就是說,我的數(shù)據(jù)庫中,主要的數(shù)據(jù)就是這兩個數(shù)據(jù)表。
在創(chuàng)建模型后,在終端輸入以下兩行代碼:
python manage.py makemigrations python manage.py migrate
這樣就可以完成數(shù)據(jù)表的創(chuàng)建,數(shù)據(jù)遷移也是這兩行代碼。同時,還會在項目應(yīng)用下生成一個migrations文件夾,記錄你的各種數(shù)據(jù)遷移指令。
看看生成的數(shù)據(jù)庫表:

上面圖中,生成了personinfo和vocation兩張表,可以自行在表中添加數(shù)據(jù)。
定義表單
表單是個啥玩意兒,我不想解釋,因為我自己也是一知半解。這個就是你的前端界面要顯示的東西,通過這個表單,可以在瀏覽器上生成網(wǎng)頁表單。怎么創(chuàng)建呢,同樣是在index目錄(項目應(yīng)用)下新建一個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('請輸入合理的薪資')
class VocationForm(forms.Form):
job = forms.CharField(max_length=20, label='職位')
title = forms.CharField(max_length=20, label='職稱',
widget=forms.widgets.TextInput(attrs={'class': 'cl'}),
error_messages={'required': '職稱不能為空'})
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 '初級' + data
簡單解釋一下,就是說我待會兒生成的網(wǎng)頁上,要顯示job、title、payment還有一個人名下拉框,這些字段以表單形式呈現(xiàn)在網(wǎng)頁上。
修改模板
模板實際上就是網(wǎng)頁上要顯示的信息,為啥叫模板呢,因為你可以自定義修改,在index.html中修改,如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{% if v.errors %}
<p>
數(shù)據(jù)出錯了,錯誤信息:{{ 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ù)其實就是views.py文件中的函數(shù),這個函數(shù)非常重要,在項目創(chuàng)建的時候自動生成,它是你的前后端連接的樞紐,不管是FBV視圖還是CBV視圖,都需要它。
先來看看這個項目中視圖函數(shù)的代碼:
from django.shortcuts import render
from django.http import HttpResponse
from index.form import VocationForm
from .models import *
def index(request):
# GET請求
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í)行實例化
v = VocationForm(**i)
else:
v = VocationForm(prefix='vv')
return render(request, 'index.html', locals())
# POST請求
else:
# 由于在GET請求設(shè)置了參數(shù)prefix
# 實例化時必須設(shè)置參數(shù)prefix,否則無法獲取POST的數(shù)據(jù)
v = VocationForm(data=request.POST, prefix='vv')
if v.is_valid():
# 獲取網(wǎng)頁控件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:
# 獲取錯誤信息,并以json格式輸出
error_msg = v.errors.as_json()
print(error_msg)
return render(request, 'index.html', locals())
其實就一個index函數(shù),不同請求方式的時候,顯示不同的內(nèi)容。這里要區(qū)分get和post請求,get是向特定資源發(fā)出請求,也就是輸入網(wǎng)址訪問網(wǎng)頁,post是向指定資源提交數(shù)據(jù)處理請求,比如提交表單,上傳文件這些。
好吧,這樣就已經(jīng)完成了項目所有的配置。
啟動項目,并在瀏覽器中輸入以下地址:http://127.0.0.1:8000/?id=1
這是個get請求,顯示內(nèi)容如下:

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

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

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

id為1的數(shù)據(jù)已經(jīng)修改成了我們設(shè)置的內(nèi)容。
至此,表單和數(shù)據(jù)交互這個小節(jié)的內(nèi)容已經(jīng)結(jié)束。
記錄感受
Django項目,創(chuàng)建之初要設(shè)置路由,如果要用到數(shù)據(jù)庫,需要配置數(shù)據(jù)庫,然后通過模型來創(chuàng)建數(shù)據(jù)表,并通過終端指令完成數(shù)據(jù)表創(chuàng)建和遷移,隨后定義表單格式,最后在視圖函數(shù)中設(shè)置各種請求方式。
感受就是兩個字,繁雜、
到此這篇關(guān)于Django在視圖中使用表單并和數(shù)據(jù)庫進(jìn)行數(shù)據(jù)交互的實現(xiàn)的文章就介紹到這了,更多相關(guān)Django 數(shù)據(jù)交互內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python爬蟲庫requests-html進(jìn)行HTTP請求HTML解析等高級功能應(yīng)用
這篇文章主要為大家介紹了Python爬蟲庫requests-html進(jìn)行HTTP請求HTML解析JavaScript渲染以及更高級的功能應(yīng)用示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-12-12
Python中使用matplotlib繪制mqtt數(shù)據(jù)實時圖像功能
這篇文章主要介紹了Python中使用matplotlib繪制mqtt數(shù)據(jù)實時圖像,本代碼中publish是一個死循環(huán),數(shù)據(jù)一直往外發(fā)送,詳細(xì)代碼跟隨小編一起通過本文學(xué)習(xí)下吧2021-09-09
pytorch GAN偽造手寫體mnist數(shù)據(jù)集方式
今天小編就為大家分享一篇pytorch GAN偽造手寫體mnist數(shù)據(jù)集方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-01-01
python基礎(chǔ)學(xué)習(xí)之如何對元組各個元素進(jìn)行命名詳解
python的元祖和列表類似,不同之處在于元祖的元素不能修改,下面這篇文章主要給大家介紹了關(guān)于python基礎(chǔ)學(xué)習(xí)之如何對元組各個元素進(jìn)行命名的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),需要的朋友可以參考下2018-07-07

