Python?Django框架中表單的用法詳解
Django保證表單的正確顯示需要添加CSRF(防止網(wǎng)站跨站請(qǐng)求偽造而默認(rèn)開啟的一種保護(hù)方式),在<form></form>之間添加
{% csrf_token %}

在項(xiàng)目settings.py中 * ‘django.middleware.csrf.CsrfViewMiddleware’, * 引入,如果沒有此中間件,手動(dòng)添加。
文件上傳
首次打開路徑是GET請(qǐng)求,如果點(diǎn)擊上傳是POST請(qǐng)求,如果文件內(nèi)容不為空,則上傳文件,上傳路徑為主項(xiàng)目下的 media/uploads/,如果路徑不存在則新建。open(os.path.join(path + myFile.name), ‘wb+’) 二進(jìn)制讀寫打開對(duì)應(yīng)文件,chunks()將文件分塊讀寫。
def upload_file(request):
if request.method == "GET":
return render(request, 'app1/upload.html')
if request.method == "POST":
myFile = request.FILES.get("myfile", None)
if myFile:
path = 'media/uploads/'
if not os.path.exists(path):
os.makedirs(path)
dest = open(os.path.join(path + myFile.name), 'wb+')
for chunk in myFile.chunks():
dest.write(chunk)
dest.close()
return HttpResponse("上傳完成")
else:
return HttpResponse("沒有上傳文件")
添加路由。


文件已經(jīng)上傳成功。
Form表單
如下新建一個(gè)form.py寫入如下代碼
from django import forms
class UserInfoForm(forms.Form):
'''用戶狀態(tài)'''
STATUS = ((None, '請(qǐng)選擇'), (0, '正常'), (1, '無效'),)
username = forms.CharField(label="用戶名稱", min_length=6, widget=forms.widgets.TextInput(
attrs={'class': 'form-control', 'placeholder': '請(qǐng)輸入用戶名稱'}
))
password = forms.CharField(label="密碼", min_length=6, max_length=10, widget=forms.widgets.PasswordInput(
attrs={'class': 'password'}, render_value=True
))
age = forms.IntegerField(label="年齡", initial=1)
mobile = forms.IntegerField(label="手機(jī)號(hào)碼")
status = forms.ChoiceField(label="用戶狀態(tài)", choices=STATUS)
createdate = forms.DateTimeField(label="創(chuàng)建時(shí)間", required=False)
表單字段
| 表單字段 | 說明 |
|---|---|
| CharField | 文本輸入 |
| InterField/FloatField/DecimalField | 數(shù)值輸入 |
| ChoiceField | 選擇輸入框 choices指定下拉列表 |
| FileField | 文件 |
| BooleanField | 復(fù)選框 |
| DateField/DateTimeField/TimeField | 時(shí)間輸入框,可以設(shè)置輸入格式 input_format=[“%Y-%m-%d %H:%M”] |
| EmailField | 郵件輸入框 |
| URLField | 路勁輸入框 |
| ModelChoiceField | 從數(shù)據(jù)庫獲取下拉列表 |
字段參數(shù)
| 字段 | 說明 |
|---|---|
| label | label標(biāo)簽 |
| label_suffix | Label標(biāo)簽統(tǒng)一后綴信息 |
| initial | 初始值 |
| help_text | 字段描述信息 |
| error_messages | 字段描述信息 |
| validators | 驗(yàn)證規(guī)則 |
| required | 是否必須 |
| disabled | 字段是否可編輯 |
| widget | 指定HTML樣式 |
widget參數(shù)
| 參數(shù) | 說明 |
|---|---|
| PasswordInput | 密碼輸入框 |
| HiddenInput | 隱藏元素 |
| Textarea | 文本域 |
| CheckboxInput | 復(fù)選框 |
| FileInput | 文件輸入框 |
| RadioSelect | 單選按鈕 |
| DateTimeInput | 時(shí)間輸入框 |
| Select | 下拉列表 |
| SelectMuitiple | 多選框 |
配置視圖和路徑顯示對(duì)應(yīng)表單
app1下的views.py
def userinfo_form(request):
if request.method == "GET":
myForm = UserInfoForm()
return render(request, 'app1/userinfo.html', {'form_obj': myForm})
userinfo.html
<html>
<head></head>
<body>
<form action="" method="POST">
{% csrf_token %} {{ form_obj.as_p }}
<input type="submit" value="提交" />
</form>
</body>
</html>
- as_p 為表單提供<p>標(biāo)簽
- as_table 為表單提供<table>標(biāo)簽
- as_ui 為表單提供<ui>標(biāo)簽
以上用了as_p,故源代碼顯示p標(biāo)簽。

表單的驗(yàn)證
- is_valid() 驗(yàn)證表單數(shù)據(jù)是否合法
- cleaned_data 獲取表單通過驗(yàn)證的數(shù)據(jù)
- errors 表單驗(yàn)證的錯(cuò)誤信息
在form中添加如下代碼
class UserInfoForm__Msg(forms.Form):
'''用戶狀態(tài)'''
STATUS = ((None, '請(qǐng)選擇'), (0, '正常'), (1, '無效'),)
username = forms.CharField(label="用戶名稱", min_length=6, widget=forms.widgets.TextInput(
attrs={'class': 'form-control', 'placeholder': '請(qǐng)輸入用戶名稱'}
), error_messages={
'required': '用戶姓名不能為空', 'min_length': '長度不能少于6位', 'invalid': '不能含有特殊字符'
})
password = forms.CharField(label="密碼", min_length=6, max_length=10, widget=forms.widgets.PasswordInput(
attrs={'class': 'password'}, render_value=True
), error_messages={
'required': '密碼不能為空', 'min_length': '密碼不能少于6位', 'max_length': '密碼不能多余10位',
})
age = forms.IntegerField(label="年齡", initial=1, validators=[age_validate], error_messages={
'required': '年齡不能為空',
})
mobile = forms.IntegerField(label="手機(jī)號(hào)碼", validators=[mobile_validate], error_messages={
'required': '手機(jī)號(hào)碼不能為空',
})
status = forms.ChoiceField(label="用戶狀態(tài)", choices=STATUS, error_messages={
'required': '用戶狀態(tài)不能為空',
})
createdate = forms.DateTimeField(label="創(chuàng)建時(shí)間", required=False)
- required 為空的時(shí)候的錯(cuò)誤信息
- invalid 格式驗(yàn)證錯(cuò)誤的信息
- min_length和max_length 長度不在設(shè)定的范圍的錯(cuò)誤信息
添加視圖
def userinfo_form_msg(request):
if request.method == "GET":
myForm = UserInfoForm__Msg()
return render(request, 'app1/userinfoform.html', {'form_obj': myForm})
else:
f = UserInfoForm__Msg(request.POST)
if f.is_valid():
print(f.cleaned_data['username'])
else:
errors = f.errors
print(errors)
return render(request, 'app1/userinfoform.html', {'form_obj': f, 'errors': errors})
return render(request, 'app1/userinfoform.html', {'form_obj': f})
模板文件
<form action="" method="POST" novalidate>
{% csrf_token %}
<p>
{{ form_obj.username.label }}:{{ form_obj.username }} {{ errors.username.0 }}
</p>
<p>{{ form_obj.password}}{{ errors.password.0 }}</p>
<p>{{ form_obj.status.label }}:{{ form_obj.status }} {{ errors.status.0 }}</p>
<p>{{ form_obj.age.label }}:{{ form_obj.age }} {{ errors.age.0 }}</p>
<p>{{ form_obj.mobile.label }}:{{ form_obj.mobile }} {{ errors.mobile.0 }}</p>
錯(cuò)誤信息匯總: {{ errors }}
<input type="submit" value="提交" />
</form>

這里還添加了表單的自我格式驗(yàn)證,獲取表單的數(shù)據(jù)
- f.clean() 獲取全部數(shù)據(jù)
- f.clean_date[] 獲取對(duì)應(yīng)值的數(shù)據(jù)
- f.data 獲取全部數(shù)據(jù)
表單模型文件上傳例子
模板文件:upload_form.html
<form enctype="multipart/form-data" action="" method="post">
{% csrf_token %} {{ form_obj.as_p }}
<br />
<input type="submit" value="文件上傳" />
<img src="media/uploads/{{ user.heading }}"
</form>模型文件
在models.py中添加模型,這里沒有主鍵默認(rèn)會(huì)生成id的主鍵
class ImgFile(models.Model):
name = models.CharField(verbose_name='用戶名稱', max_length=300, default="")
heading = models.FileField(verbose_name='文件名', upload_to='media/uploads/')
def __str__(self):
return self.name
class Meta:
verbose_name = ' 用戶頭像信息'
db_table = 'user_img'
表單模型 form.py
class ImgFileForm(forms.Form):
name = forms.CharField()
heading = forms.FileField()
視圖模型
如果上傳了文件,將文件保存在對(duì)應(yīng)的目錄下,并返回文件的信息。
def ingfileform(request):
if request.method == "GET":
f = ImgFileForm()
return render(request, 'app1/upload_form.html', {'form_obj': f})
else:
f = ImgFileForm(request.POST, request.FILES)
if f.is_valid():
name = f.cleaned_data['name']
heading = f.cleaned_data['heading']
path = 'media/uploads/'
if not os.path.exists(path):
os.makedirs(path)
dest = open(os.path.join(path + heading.name), 'wb+')
for chunk in heading.chunks():
dest.write(chunk)
dest.close()
userimg = ImgFile()
userimg.name = name
userimg.heading = heading
userimg.save()
print('上傳成功')
return render(request, 'app1/upload_form.html', {'form_obj': f, 'user': userimg})
else:
print(f.errors)
路由
re_path 配置了可以直接在瀏覽器訪問對(duì)應(yīng)的文件,
from django.urls import path, include, re_path
from django.views.static import serve
from mywed import settings
path('app1/userimg/', views.ingfileform),
re_path('media/uploads/(?P<path>.*)', serve,
{"document_root": settings.MEDIA_ROOT}),
settings.py
這里路徑在項(xiàng)目文件中設(shè)置便于統(tǒng)一,在實(shí)際的應(yīng)用中也應(yīng)該多在公共文件中設(shè)置
MEDIA_URL = "media/uploads/" MEDIA_ROOT = os.path.join(MEDIA_URL, "")


db中也登陸了對(duì)應(yīng)的信息

模型表單
Django提供了ModelForm可以直接和模型關(guān)聯(lián),省略了Form表單中定義的操作。
AJAX
模板文件,為了能夠正常的訪問,必須添加csrfmiddlewaretoken或者在視圖函數(shù)中注釋@csrf_exempt,建議使用第一種方式
用戶名:<input type="text" id="username"></input>
密碼:<input type="password" id="password"></input>
{% csrf_token %}
<button id="submit">提交</button>
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
<script>
$("#submit").click(function(){
var csrf = $('input[name="csrfmiddlewaretoken"]').val();
$.ajax({
url: '/app1/ajax_login_data',
type: "post",
data: {
'username': $("#username").val(),
'password': $("#password").val(),
'csrfmiddlewaretoken': csrf
},
success: function(data){
console.log(data)
},
error: function(jqXHR, textStatus, err){
console.log(arguments);
}
});
});
</script>
視圖文件
from django.views.decorators.csrf import csrf_exempt
def ajax_login(request):
return render(request, 'app1/ajax.html')
# @csrf_exempt
def ajax_login_data(request):
if request.method == "GET":
HttpResponse("內(nèi)部自己的url")
username = request.POST.get('username')
password = request.POST.get('password')
print(username)
if username == 'admin' and password == '123456':
return JsonResponse({
'code': 1,
'msg': "登陸成功"
})
else:
print("222")
return JsonResponse({
'code': 0,
'msg': "登陸失敗"

這里使用的是網(wǎng)上的jquery地址,也可在settings.py匹配如下,在網(wǎng)站根目錄中創(chuàng)建static目錄,放入jquery文件。
<script src=“/statics/jquery.min.js”></script>
STATIC_URL = '/statics/'
???????STATICFILES_DIRS = [
os.path.join(BASE_DIR, "statics"),
]
以上就是Python Django框架中表單的用法詳解的詳細(xì)內(nèi)容,更多關(guān)于Python Django表單的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
使用Python神器對(duì)付12306變態(tài)驗(yàn)證碼
這篇文章主要介紹了使用Python神器對(duì)付12306變態(tài)驗(yàn)證碼的相關(guān)資料,需要的朋友可以參考下2016-01-01
Python使用PyMySql增刪改查Mysql數(shù)據(jù)庫的實(shí)現(xiàn)
PyMysql是Python中用于連接MySQL數(shù)據(jù)庫的一個(gè)第三方庫,本文主要介紹了Python使用PyMySql增刪改查Mysql數(shù)據(jù)庫的實(shí)現(xiàn),具有一定的參考價(jià)值,感興趣的可以了解一下2024-01-01
pandas string轉(zhuǎn)dataframe的方法
下面小編就為大家分享一篇pandas string轉(zhuǎn)dataframe的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-04-04
Python批量將csv文件轉(zhuǎn)化成xml文件的實(shí)例
將 csv 格式轉(zhuǎn)換成xml格式有許多方法,可以用數(shù)據(jù)庫的方式,也有許多軟件可以將 csv 轉(zhuǎn)換成xml。但是比較麻煩,本文利用 Python 一鍵批量將 csv 文件轉(zhuǎn)化成 xml 文件。2021-05-05
Python函數(shù)參數(shù)中的*與**運(yùn)算符
這篇文章主要介紹了Python函數(shù)參數(shù)中的*與**運(yùn)算符,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-04-04

