Django 實(shí)現(xiàn)圖片上傳和顯示過程詳解
第1章 新建工程和創(chuàng)建app
新建工程和創(chuàng)建app就不用貼出來了,我這里是測試圖片上傳的功能能否實(shí)現(xiàn),所以項(xiàng)目都是新的,正常在以有的app下就可以
第2章 模型層:
2.1創(chuàng)建數(shù)據(jù)庫
from django.dbimport models # Create your models here. class User(models.Model): name= models.CharField(max_length=50) # upload_to 指定上傳文件位置 # 這里指定存放在img/ 目錄下 headimg = models.FileField(upload_to="img/") # 返回名稱 def__str__(self): returnself.name
2.2初始化數(shù)據(jù)庫:
(mypy3) ➜ BBS python manage.py makemigrations Migrations for 'app01': app01/migrations/0001_initial.py - Create model User (mypy3) ➜ BBS python manage.py migrate Operations to perform: Apply all migrations: admin, app01, auth, contenttypes, sessions
第3章 修改配置文件
3.1settings中增加如下配置:
MEDIA_ROOT= os.path.join(BASE_DIR, 'media').replace("\\", "/") MEDIA_URL = '/media/'
3.2工程的urls文件:
from django.conf.urlsimport url from django.contrib import admin from django.urls import path, include from django.conf.urls.static import static from django.conf import settings urlpatterns = [ url(r'^admin/', admin.site.urls), # url(r'^regsiter/', views.regsiter), # url(r'', TemplateView.as_view(template_name="app01/index.html")), path('app01/', include('app01.urls')) ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
3.3app:
from django.urlsimport path from . import views app_name = 'app01' urlpatterns = [ path('add/', views.add, name='add'), # path('index/', views.index, name='index'), ]
3.4修改模版配置:
TEMPLATES= [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ]
第4章 數(shù)據(jù)校驗(yàn)?zāi)K:
數(shù)據(jù)需要校驗(yàn)的情況下,如果你不想校驗(yàn),這個(gè)可以忽略
4.1在app下創(chuàng)建forms文件:
from django import forms # 表單類用以生成表單 class AddForm(forms.Form): name = forms.CharField() headimg = forms.FileField()
第5章 視圖層:
5.1編寫圖片處理邏輯
from django.shortcutsimport render from .models import User from .forms import AddForm # Create your views here. def add(request): # 判斷是否為post 方法提交 ifrequest.method == "POST": af = AddForm(request.POST, request.FILES) # 判斷表單值是否和法 ifaf.is_valid(): name = af.cleaned_data['name'] headimg = af.cleaned_data['headimg'] user = User(name=name, headimg=headimg) user.save() returnrender(request, 'app01/index.html', context={"user":user}) else: af = AddForm() returnrender(request, 'app01/add.html', context={"af":af})
第6章 模版層:
上傳的html
<!-- templates/users/add.html --> <!doctype html> <html> <head> <title>Add</title> <meta charset="utf-8"> </head> <body> <h1>Add!</h1> <form method="post" enctype="multipart/form-data" action="{% url'app01:add' %}"> {%csrf_token %} {{ af.as_p }} <inputtype="submit" value="OK"/> </form> </body> </html>
查看的html
<!-- templates/users/index.html --> <!doctype html> <html> <head> <title>Detail</title> <meta charset="utf-8"> </head> <body> <p>{{user.name}}</p> <img width="50%" height="50%"src="/media/{{ user.headimg }}"> </body> </html>
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Python面向?qū)ο缶幊剃P(guān)鍵深度探索類與對象
這篇文章主要為大家介紹了Python面向?qū)ο缶幊剃P(guān)鍵深度探索類與對象示例解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-05-05python中的?sorted()函數(shù)和sort()方法區(qū)別
這篇文章主要介紹了python中的?sorted()函數(shù)和sort()方法,首先看sort()方法,sort方法只能對列表進(jìn)行操作,而sorted可用于所有的可迭代對象。具體內(nèi)容需要的小伙伴可以參考下面章節(jié)2022-02-02在python中對變量判斷是否為None的三種方法總結(jié)
今天小編就為大家分享一篇在python中對變量判斷是否為None的三種方法總結(jié),具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-01-01Django 實(shí)現(xiàn)外鍵去除自動(dòng)添加的后綴‘_id’
今天小編就為大家分享一篇Django 實(shí)現(xiàn)外鍵去除自動(dòng)添加的后綴‘_id’,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-11-11Python協(xié)程的四種實(shí)現(xiàn)方式總結(jié)
今天繼續(xù)給大家介紹Python關(guān)知識,本文主要內(nèi)容是Python協(xié)程的四種實(shí)現(xiàn)方式。文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2023-01-01Python關(guān)于時(shí)間序列calendar模塊的深入講解
calendar,是與日歷相關(guān)的模塊。calendar模塊文件里定義了很多類型,主要有Calendar,TextCalendar以及HTMLCalendar類型。其中,Calendar是TextCalendar與HTMLCalendar的基類2021-11-11