亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Python?Django框架中表單的用法詳解

 更新時(shí)間:2022年06月24日 09:59:49   作者:我的天才女友  
這篇文章主要為大家詳細(xì)介紹了Python?Django框架中表單的用法,例如表單的驗(yàn)證以及利用表單實(shí)現(xiàn)文件上傳等,感興趣的小伙伴可以了解一下

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ù)

字段說明
labellabel標(biāo)簽
label_suffixLabel標(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': '長(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中添加模型,這里沒有主鍵默認(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實(shí)現(xiàn)過濾敏感詞

    python實(shí)現(xiàn)過濾敏感詞

    這篇文章主要介紹了python如何實(shí)現(xiàn)過濾敏感詞,幫助大家更好的理解和學(xué)習(xí)使用python,感興趣的朋友可以了解下
    2021-05-05
  • 使用Python神器對(duì)付12306變態(tài)驗(yà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)

    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
  • 詳解Python中type與object的恩怨糾葛

    詳解Python中type與object的恩怨糾葛

    估計(jì)很多人都會(huì)有這樣一個(gè)困惑,object?的類型是?type,但它同時(shí)又是?type?的基類,這是怎么做到的?帶著這個(gè)疑問,我們開始本文的內(nèi)容
    2023-04-04
  • 一些Python?5行代碼的神奇操作匯總

    一些Python?5行代碼的神奇操作匯總

    最開始學(xué)習(xí)?Python,不需要太過復(fù)雜,下面這篇文章主要給大家介紹了關(guān)于Python?5行代碼的神奇操作,文中通過示例代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2022-04-04
  • pandas string轉(zhuǎn)dataframe的方法

    pandas string轉(zhuǎn)dataframe的方法

    下面小編就為大家分享一篇pandas string轉(zhuǎn)dataframe的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2018-04-04
  • Python批量將csv文件轉(zhuǎn)化成xml文件的實(shí)例

    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字符串的索引與切片

    Python字符串的索引與切片

    這篇文章主要介紹了Python字符串的索引與切片,文章圍繞主題展開詳細(xì)的相關(guān)資料,需要的小伙伴可以參考一下
    2022-04-04
  • 基于pycharm導(dǎo)入模塊顯示不存在的解決方法

    基于pycharm導(dǎo)入模塊顯示不存在的解決方法

    今天小編就為大家分享一篇基于pycharm導(dǎo)入模塊顯示不存在的解決方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2018-10-10
  • Python函數(shù)參數(shù)中的*與**運(yùn)算符

    Python函數(shù)參數(shù)中的*與**運(yùn)算符

    這篇文章主要介紹了Python函數(shù)參數(shù)中的*與**運(yùn)算符,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2021-04-04

最新評(píng)論