您好,登錄后才能下訂單哦!
本篇內(nèi)容介紹了“Python Django框架中表單怎么使用”的有關(guān)知識(shí),在實(shí)際案例的操作過(guò)程中,不少人都會(huì)遇到這樣的困境,接下來(lái)就讓小編帶領(lǐng)大家學(xué)習(xí)一下如何處理這些情況吧!希望大家仔細(xì)閱讀,能夠?qū)W有所成!
Django保證表單的正確顯示需要添加CSRF(防止網(wǎng)站跨站請(qǐng)求偽造而默認(rèn)開(kāi)啟的一種保護(hù)方式),在<form></form>之間添加
{% csrf_token %}
在項(xiàng)目settings.py中 * ‘django.middleware.csrf.CsrfViewMiddleware’, * 引入,如果沒(méi)有此中間件,手動(dòng)添加。
首次打開(kāi)路徑是GET請(qǐng)求,如果點(diǎn)擊上傳是POST請(qǐng)求,如果文件內(nèi)容不為空,則上傳文件,上傳路徑為主項(xiàng)目下的 media/uploads/,如果路徑不存在則新建。open(os.path.join(path + myFile.name), ‘wb+’) 二進(jìn)制讀寫打開(kāi)對(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("沒(méi)有上傳文件")
添加路由。
文件已經(jīng)上傳成功。
如下新建一個(gè)form.py寫入如下代碼
from django import forms class UserInfoForm(forms.Form): '''用戶狀態(tài)''' STATUS = ((None, '請(qǐng)選擇'), (0, '正常'), (1, '無(wú)效'),) 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)
表單字段 | 說(shuō)明 |
---|---|
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ù)庫(kù)獲取下拉列表 |
字段 | 說(shuō)明 |
---|---|
label | label標(biāo)簽 |
label_suffix | Label標(biāo)簽統(tǒng)一后綴信息 |
initial | 初始值 |
help_text | 字段描述信息 |
error_messages | 字段描述信息 |
validators | 驗(yàn)證規(guī)則 |
required | 是否必須 |
disabled | 字段是否可編輯 |
widget | 指定HTML樣式 |
參數(shù) | 說(shuō)明 |
---|---|
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)簽。
is_valid() 驗(yàn)證表單數(shù)據(jù)是否合法
cleaned_data 獲取表單通過(guò)驗(yàn)證的數(shù)據(jù)
errors 表單驗(yàn)證的錯(cuò)誤信息
在form中添加如下代碼
class UserInfoForm__Msg(forms.Form): '''用戶狀態(tài)''' STATUS = ((None, '請(qǐng)選擇'), (0, '正常'), (1, '無(wú)效'),) username = forms.CharField(label="用戶名稱", min_length=6, widget=forms.widgets.TextInput( attrs={'class': 'form-control', 'placeholder': '請(qǐng)輸入用戶名稱'} ), error_messages={ 'required': '用戶姓名不能為空', 'min_length': '長(zhǎng)度不能少于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 長(zhǎng)度不在設(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中添加模型,這里沒(méi)有主鍵默認(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 配置了可以直接在瀏覽器訪問(wèn)對(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表單中定義的操作。
模板文件,為了能夠正常的訪問(wèn),必須添加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框架中表單怎么使用”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識(shí)可以關(guān)注億速云網(wǎng)站,小編將為大家輸出更多高質(zhì)量的實(shí)用文章!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。