最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

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

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

Django保證表單的正確顯示需要添加CSRF(防止網(wǎng)站跨站請求偽造而默認開啟的一種保護方式),在<form></form>之間添加

{% csrf_token %}

在項目settings.py中 * ‘django.middleware.csrf.CsrfViewMiddleware’, * 引入,如果沒有此中間件,手動添加。

文件上傳

首次打開路徑是GET請求,如果點擊上傳是POST請求,如果文件內(nèi)容不為空,則上傳文件,上傳路徑為主項目下的 media/uploads/,如果路徑不存在則新建。open(os.path.join(path + myFile.name), ‘wb+’) 二進制讀寫打開對應文件,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表單

如下新建一個form.py寫入如下代碼

from django import forms

class UserInfoForm(forms.Form):
    '''用戶狀態(tài)'''
    STATUS = ((None, '請選擇'), (0, '正常'), (1, '無效'),)
    username = forms.CharField(label="用戶名稱", min_length=6, widget=forms.widgets.TextInput(
        attrs={'class': 'form-control', 'placeholder': '請輸入用戶名稱'}
    ))
    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="手機號碼")
    status = forms.ChoiceField(label="用戶狀態(tài)", choices=STATUS)
    createdate = forms.DateTimeField(label="創(chuàng)建時間", required=False)

表單字段

表單字段說明
CharField文本輸入
InterField/FloatField/DecimalField數(shù)值輸入
ChoiceField選擇輸入框 choices指定下拉列表
FileField文件
BooleanField復選框
DateField/DateTimeField/TimeField時間輸入框,可以設置輸入格式 input_format=[“%Y-%m-%d %H:%M”]
EmailField郵件輸入框
URLField路勁輸入框
ModelChoiceField從數(shù)據(jù)庫獲取下拉列表

字段參數(shù)

字段說明
labellabel標簽
label_suffixLabel標簽統(tǒng)一后綴信息
initial初始值
help_text字段描述信息
error_messages字段描述信息
validators驗證規(guī)則
required是否必須
disabled字段是否可編輯
widget指定HTML樣式

widget參數(shù)

參數(shù)說明
PasswordInput密碼輸入框
HiddenInput隱藏元素
Textarea文本域
CheckboxInput復選框
FileInput文件輸入框
RadioSelect單選按鈕
DateTimeInput時間輸入框
Select下拉列表
SelectMuitiple多選框

配置視圖和路徑顯示對應表單

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>標簽
  • as_table 為表單提供<table>標簽
  • as_ui 為表單提供<ui>標簽

以上用了as_p,故源代碼顯示p標簽。

表單的驗證

  • is_valid() 驗證表單數(shù)據(jù)是否合法
  • cleaned_data 獲取表單通過驗證的數(shù)據(jù)
  • errors 表單驗證的錯誤信息

在form中添加如下代碼

class UserInfoForm__Msg(forms.Form):
    '''用戶狀態(tài)'''
    STATUS = ((None, '請選擇'), (0, '正常'), (1, '無效'),)
    username = forms.CharField(label="用戶名稱", min_length=6, widget=forms.widgets.TextInput(
        attrs={'class': 'form-control', 'placeholder': '請輸入用戶名稱'}
    ), 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="手機號碼", validators=[mobile_validate], error_messages={
        'required': '手機號碼不能為空',
    })
    status = forms.ChoiceField(label="用戶狀態(tài)", choices=STATUS, error_messages={
        'required': '用戶狀態(tài)不能為空',
    })
    createdate = forms.DateTimeField(label="創(chuàng)建時間", required=False)
  • required 為空的時候的錯誤信息
  • invalid 格式驗證錯誤的信息
  • min_length和max_length 長度不在設定的范圍的錯誤信息

添加視圖

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>
  錯誤信息匯總: {{ errors }}
  <input type="submit" value="提交" />
</form>

這里還添加了表單的自我格式驗證,獲取表單的數(shù)據(jù)

  • f.clean() 獲取全部數(shù)據(jù)
  • f.clean_date[] 獲取對應值的數(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中添加模型,這里沒有主鍵默認會生成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()

視圖模型

如果上傳了文件,將文件保存在對應的目錄下,并返回文件的信息。

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 配置了可以直接在瀏覽器訪問對應的文件,

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

這里路徑在項目文件中設置便于統(tǒng)一,在實際的應用中也應該多在公共文件中設置

MEDIA_URL = "media/uploads/"
MEDIA_ROOT = os.path.join(MEDIA_URL, "")

db中也登陸了對應的信息

模型表單

Django提供了ModelForm可以直接和模型關聯(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框架中表單的用法詳解的詳細內(nèi)容,更多關于Python Django表單的資料請關注腳本之家其它相關文章!

相關文章

  • Python cookie的保存與讀取、SSL講解

    Python cookie的保存與讀取、SSL講解

    在本篇文章里小編給大家整理了關于Python cookie的保存與讀取、SSL講解,需要的朋友們可以學習下。
    2020-02-02
  • 如何利用PyQt5制作一個簡單的登錄界面

    如何利用PyQt5制作一個簡單的登錄界面

    初學者制作登錄界面時常遇到網(wǎng)上代碼看不懂、不會用、用不了的問題,下面這篇文章主要給大家介紹了關于如何利用PyQt5制作一個簡單的登錄界面,文中通過實例代碼介紹的非常詳細,需要的朋友可以參考下
    2022-06-06
  • 將Dataframe數(shù)據(jù)轉化為ndarry數(shù)據(jù)的方法

    將Dataframe數(shù)據(jù)轉化為ndarry數(shù)據(jù)的方法

    今天小編就為大家分享一篇將Dataframe數(shù)據(jù)轉化為ndarry數(shù)據(jù)的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-06-06
  • python通過getopt模塊如何獲取執(zhí)行的命令參數(shù)詳解

    python通過getopt模塊如何獲取執(zhí)行的命令參數(shù)詳解

    這篇文章主要給大家介紹了關于python通過getopt模塊如何獲取執(zhí)行的命令參數(shù)的相關資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧。
    2017-12-12
  • python函數(shù)遞歸調(diào)用的實現(xiàn)

    python函數(shù)遞歸調(diào)用的實現(xiàn)

    本文主要介紹了python函數(shù)遞歸調(diào)用的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2023-05-05
  • OpenCV+python實現(xiàn)實時目標檢測功能

    OpenCV+python實現(xiàn)實時目標檢測功能

    這篇文章主要介紹了OpenCV+python實現(xiàn)實時目標檢測功能,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2020-06-06
  • PyCharm Ctrl+Shift+F 失靈的簡單有效解決操作

    PyCharm Ctrl+Shift+F 失靈的簡單有效解決操作

    這篇文章主要介紹了PyCharm Ctrl+Shift+F 失靈的簡單有效解決操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2021-01-01
  • 詳解如何使用Python提取視頻文件中的音頻

    詳解如何使用Python提取視頻文件中的音頻

    在多媒體處理中,有時我們需要從視頻文件中提取音頻,本文為大家整理了幾種使用Python編程語言提取視頻文件中的音頻的方法,大家可以根據(jù)需要進行選擇
    2025-03-03
  • python實現(xiàn)不同數(shù)據(jù)庫間數(shù)據(jù)同步功能

    python實現(xiàn)不同數(shù)據(jù)庫間數(shù)據(jù)同步功能

    這篇文章主要介紹了python實現(xiàn)不同數(shù)據(jù)庫間數(shù)據(jù)同步功能,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2021-02-02
  • 在 Jupyter 中重新導入特定的 Python 文件(場景分析)

    在 Jupyter 中重新導入特定的 Python 文件(場景分析)

    Jupyter 是數(shù)據(jù)分析領域非常有名的開發(fā)環(huán)境,使用 Jupyter 寫數(shù)據(jù)分析相關的代碼會大大節(jié)約開發(fā)時間。這篇文章主要介紹了在 Jupyter 中如何重新導入特定的 Python 文件,需要的朋友可以參考下
    2019-10-10

最新評論

耒阳市| 启东市| 陵水| 民乐县| 普洱| 阿合奇县| 桃园县| 普陀区| 巴里| 潜江市| 新龙县| 宁南县| 芜湖市| 枣强县| 岳阳县| 和平区| 分宜县| 西吉县| 武隆县| 循化| 宜黄县| 海林市| 永州市| 彰化县| 玉环县| 凭祥市| 宣武区| 大邑县| 洪雅县| 林西县| 长汀县| 福州市| 厦门市| 黄浦区| 七台河市| 襄樊市| 晋江市| 绍兴市| 明水县| 灵寿县| 宜川县|