django中ImageField的使用詳解
今天完善作業(yè)寫的訂單系統(tǒng),主要是給每一個(gè)菜品增加圖片,看起來(lái)美觀一些,但是沒(méi)想到這個(gè)小小的需求花了我一天時(shí)間,記錄下來(lái),算增長(zhǎng)知識(shí)了。
使用流程1.配置setting文件MEDIA_ROOT代表的是上傳圖片的根目錄,MEDIA_URL代表的是訪問(wèn)文件時(shí)url的前綴。
# 圖片儲(chǔ)存根路徑MEDIA_ROOT = join(’media’)# 圖片訪問(wèn)urlMEDIA_URL = ’/IMG/’2.model里面增加ImageField屬性
up_load一定要配置,代表你最后的圖片會(huì)存儲(chǔ)到MEDIA_ROOT/up_load(實(shí)際上是你賦予的名稱)這個(gè)文件夾中。
class Menu(models.Model): ''' 餐品數(shù)據(jù)庫(kù) ''' ID = models.BigAutoField(primary_key=True,editable=False) lastEditTime = models.DateTimeField(auto_now_add=True) merchantID = models.ForeignKey(Usr, verbose_name='商家賬號(hào)', on_delete=models.CASCADE,to_field=’ID’) itemName = models.CharField(max_length=20,verbose_name='餐品名') itemText = models.TextField(verbose_name='餐品簡(jiǎn)介') price = models.FloatField(verbose_name='餐品價(jià)格') ################# up_load代表你上傳圖片所存儲(chǔ)的文件夾名字 picture = models.ImageField(verbose_name=’餐品圖片’,null=True,upload_to=’img/’) class Meta: db_table = 'Menu' verbose_name = '餐品數(shù)據(jù)表' ordering=[’-lastEditTime’]3.Form表單類
本項(xiàng)目使用的是django自帶的Form表單類進(jìn)行數(shù)據(jù)的傳遞。
class MerchantDish(forms.Form): ''' 商家菜品提交表單 ''' itemName = forms.CharField(max_length=20,label='餐品名') itemText = forms.CharField(max_length=300,label='餐品簡(jiǎn)介') price = forms.FloatField(label='餐品價(jià)格') picture = forms.ImageField(label=’餐品圖片’)4.html模板文件(增加菜品)
注意一定要添加:enctype=“multipart/form-data”。
<form action='updateDish_post/' method='post' enctype='multipart/form-data'> {% csrf_token %} {{form.as_p}} <button type='submit'>修改</button> <button type='button'><a href='http://www.gepszalag.com/MerchantSystem/DelDish/{{dishID}}/' rel='external nofollow' >刪除</a></button></form>5.顯示菜品的html模板文件
重要的是src中路徑的配置,有兩種方法,建議法一,自己感覺(jué)比較安全,就算沒(méi)有picture時(shí)也不會(huì)報(bào)錯(cuò)。(注意:可調(diào)整圖片顯示大小)
法一:/IMG(你自己定義的MEDIA_URL)/{{dish.picture}} ----dish代表后端傳來(lái)的菜品,dish.picture代表你使用的這個(gè)類中的那個(gè)有ImageField屬性的字段;
法二:{{dish.picture.url}} 因?yàn)镮mageField是文件類,里面有三個(gè)屬性name、path、url可以直接訪問(wèn)。
{% for dish in menu %}<!--將目錄的數(shù)據(jù)展示在html中--><!-- 提交到一個(gè)含參數(shù)的url注意后端的接收 --><form action='/MerchantSystem/Dish/{{dish.ID}}/' method='post'> {% csrf_token %} <li class='media'> <div ><img src='https://rkxy.com.cn/IMG/{{dish.picture}}' alt=''> </div> <div class='media-body'> <h4 class='media-heading'><button type=’submit’ >菜名:{{dish.itemName|default:'Null'}}</button><span class='label label-default'> 價(jià)格:{{dish.price|default:'Null'}}</span> </h4> 簡(jiǎn)介:{{dish.itemText|default:'Null'}} </div> </li></form>{% empty %}<!--若中無(wú)數(shù)據(jù)展示如下內(nèi)容--><p>暫無(wú)數(shù)據(jù)..</p>{% endfor %} {% endblock tableBody %}6.路徑靜態(tài)化
在所有的url中都要配置如下:urlpatterns + static…
from django.conf import settingsfrom django.conf.urls.static import staticurlpatterns = [ path(’’, views.base_view, name = 'base'),# 顧客服務(wù)系統(tǒng) path(’order/<int:dishID>/’, views.order_view),# 訂單詳情 path(’order/<int:dishID>/submit/’,views.order_submit),# 提交訂單 path(’pay/<int:orderID>/’, views.pay_view),# 繳費(fèi) path(’pay/<int:orderID>/submit/’,views.pay_submit),#確認(rèn)賬單 path(’order/list/’,views.order_list_view),#歷史訂單列表 path(’order/confirm/<int:orderID>/’,views.order_confirm),#訂單確認(rèn)收到 path(’order/comment/<int:orderID>/’,views.comment),#到達(dá)相應(yīng)菜品的評(píng)論界面 path(’order/comment_post/<int:orderID>/’,views.comment_post)#提交評(píng)論] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)7.修改上傳的圖片
首先用form表單上傳圖片,檢查有效之后,把cleaned_data中的picture數(shù)據(jù)賦值給要更新對(duì)象中的picture屬性,最后save即可。代碼如下:
def updateDish_post(request,dishID): ''' 接受修改菜品的請(qǐng)求 ''' dish_form = MerchantDish(request.POST,request.FILES) if dish_form.is_valid() : dish = Menu.objects.get(ID = dishID) dish.itemName = dish_form.cleaned_data[’itemName’] dish.itemText = dish_form.cleaned_data[’itemText’] dish.price = dish_form.cleaned_data[’price’] dish.picture = dish_form.cleaned_data[’picture’] dish.save() # dishChange = dish_form.clean()return redirect(’/MerchantSystem/’) elif dish_form.errors is not None: print(dish_form.errors) return HttpResponse(str(dish_form.errors))8.設(shè)置默認(rèn)圖片
這個(gè)步驟我查了好久的資料,但是都不行,好像不可以直接在model.py文件中設(shè)置default,我最后都快放棄了,但是自己還是憑運(yùn)氣試出來(lái)了,不知道原理,但還是放在這,希望對(duì)大家有幫助。方法是在顯示圖片的html模板中的src處寫一個(gè)default,代碼如下:dish是后端傳過(guò)來(lái)的參數(shù),default指向的是默認(rèn)圖片所在的位置。
<div ><!-- {{dish.url|default:'Null'}} --><img src='https://rkxy.com.cn/IMG/{{dish.picture|default:’img/default.jpg’}}' alt=''> </div>參考資料:
ImageField的使用
默認(rèn)圖片的賦值(感覺(jué)方法不行)
到此這篇關(guān)于django中ImageField的使用詳解的文章就介紹到這了,更多相關(guān)django ImageField 內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. 不使用XMLHttpRequest對(duì)象實(shí)現(xiàn)Ajax效果的方法小結(jié)2. 用xslt將xml解析成xhtml的代碼3. Ajax實(shí)現(xiàn)省市縣三級(jí)聯(lián)動(dòng)4. ASP.NET MVC使用Log4Net記錄異常日志并跳轉(zhuǎn)到靜態(tài)頁(yè)5. Ajax原理與應(yīng)用案例快速入門教程6. python cv2圖像質(zhì)量壓縮的算法示例7. 如何從外部瀏覽開(kāi)啟Android App8. python3.6環(huán)境下安裝freetype庫(kù)和基本使用方法(推薦)9. XML和YAML的使用方法10. PHP程序員簡(jiǎn)單的開(kāi)展服務(wù)治理架構(gòu)操作詳解(一)
