在 Django 專案中處理映像上傳時,可能會出現需要強制執行特定尺寸的情況,例如確保上傳的影像是矩形(而不是正方形)。這對於個人資料標題、橫幅或需要非方形格式的媒體特別有用。
在本文中,我們將使用 Django 驗證系統和 Pillow 函式庫逐步介紹一個簡單的解決方案。
先決條件
在實施解決方案之前,請確保安裝了以下相依性:
- Django(用於網路框架功能)
- 枕頭(用於影像處理)
如果您沒有安裝 Pillow,您可以使用以下方式添加它:
python -m pip install pillow
編寫驗證器
要驗證上傳的影像是否為長方形,我們需要檢查影像的寬度和高度。如果兩個尺寸相等,則表示圖像是正方形,我們將引發驗證錯誤。
這是自訂驗證器的程式碼:
from django.core.exceptions import ValidationError from PIL import Image def validate_rectangular_image(image): """ Validator to ensure an uploaded image is rectangular and not square. """ image = Image.open(image) # Open the uploaded image using Pillow width, height = image.size # Extract dimensions if width == height: # Check if image is square raise ValidationError("Uploaded image must be rectangular (not square).") return image
將驗證器與 Django 模型集成
要在 Django 應用程式中使用此驗證器,您可以將其新增至模型欄位。例如,假設您的模型中有一個用於使用者個人資料橫幅的 ImageField:
from django.db import models from .validators import validate_rectangular_image # Import the custom validator class Profile(models.Model): name = models.CharField(max_length=100) banner_image = models.ImageField( upload_to='banners/', validators=[validate_rectangular_image], help_text="Please upload a rectangular image for the banner." ) def __str__(self): return self.name
運作原理:
- 每當檔案上傳到banner_image欄位時,都會呼叫validate_rectangle_image函數。
- 如果圖像是正方形,則會引發 ValidationError,從而阻止保存檔案。
- 只有矩形圖片才會通過驗證並成功上傳。
處理表單中的驗證錯誤
如果您使用 Django 表單進行圖片上傳,當使用者提交無效圖像時,將會向使用者顯示錯誤。
例如,一個簡單的表單可能如下所示:
from django import forms from .models import Profile class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = ['name', 'banner_image']
當使用者上傳方形圖片時,他們會看到錯誤訊息:
「上傳的影像必須是長方形(不是正方形)。」
測試驗證器
您可以嘗試上傳正方形和矩形圖像來測試功能。
方形影像(例如 300x300):
驗證器將拒絕該檔案並引發 ValidationError。矩形影像(例如 400x300):
驗證器將接受該文件,並且圖像將成功上傳。
最後的註釋
透過使用此方法,您可以在 Django 應用程式中無縫地強制執行圖片尺寸要求。 Pillow 庫可以輕鬆處理圖像大小,而 Django 的驗證系統可以讓您輕鬆整合自訂邏輯。
要點:
- 使用 Pillow 擷取影像尺寸。
- 當上傳的圖像不符合您的標準時引發驗證錯誤。
- 將驗證器整合到 Django 模型中以確保資料完整性。
透過結合 Django 和 Pillow,您可以創建強大且靈活的圖像上傳規則,從而提高 Web 應用程式的品質。
編碼愉快! ?
以上是如何使用 Python 驗證 Django 中的矩形圖像的詳細內容。更多資訊請關注PHP中文網其他相關文章!

toAppendElementStoApythonList,usetheappend()方法forsingleements,Extend()formultiplelements,andinsert()forspecificpositions.1)useeAppend()foraddingoneOnelementAttheend.2)useextendTheEnd.2)useextendexendExendEnd(

TocreateaPythonlist,usesquarebrackets[]andseparateitemswithcommas.1)Listsaredynamicandcanholdmixeddatatypes.2)Useappend(),remove(),andslicingformanipulation.3)Listcomprehensionsareefficientforcreatinglists.4)Becautiouswithlistreferences;usecopy()orsl

金融、科研、医疗和AI等领域中,高效存储和处理数值数据至关重要。1)在金融中,使用内存映射文件和NumPy库可显著提升数据处理速度。2)科研领域,HDF5文件优化数据存储和检索。3)医疗中,数据库优化技术如索引和分区提高数据查询性能。4)AI中,数据分片和分布式训练加速模型训练。通过选择适当的工具和技术,并权衡存储与处理速度之间的trade-off,可以显著提升系统性能和可扩展性。

pythonarraysarecreatedusiseThearrayModule,notbuilt-Inlikelists.1)importThearrayModule.2)指定tefifythetypecode,例如,'i'forineizewithvalues.arreaysofferbettermemoremorefferbettermemoryfforhomogeNogeNogeNogeNogeNogeNogeNATATABUTESFELLESSFRESSIFERSTEMIFICETISTHANANLISTS。

除了shebang線,還有多種方法可以指定Python解釋器:1.直接使用命令行中的python命令;2.使用批處理文件或shell腳本;3.使用構建工具如Make或CMake;4.使用任務運行器如Invoke。每個方法都有其優缺點,選擇適合項目需求的方法很重要。

ForhandlinglargedatasetsinPython,useNumPyarraysforbetterperformance.1)NumPyarraysarememory-efficientandfasterfornumericaloperations.2)Avoidunnecessarytypeconversions.3)Leveragevectorizationforreducedtimecomplexity.4)Managememoryusagewithefficientdata

Inpython,ListSusedynamicMemoryAllocationWithOver-Asalose,而alenumpyArraySallaySallocateFixedMemory.1)listssallocatemoremoremoremorythanneededinentientary上,respizeTized.2)numpyarsallaysallaysallocateAllocateAllocateAlcocateExactMemoryForements,OfferingPrediCtableSageButlessemageButlesseflextlessibility。

Inpython,YouCansspecthedatatAtatatPeyFelemereModeRernSpant.1)Usenpynernrump.1)Usenpynyp.dloatp.dloatp.ploatm64,formor professisconsiscontrolatatypes。


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

mPDF
mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

SublimeText3 Linux新版
SublimeText3 Linux最新版

SublimeText3漢化版
中文版,非常好用

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

EditPlus 中文破解版
體積小,語法高亮,不支援程式碼提示功能