python 3.5
django 1.10.6html
django-admin startproject testupload
cd testupload python manage.py startapp uploadpic
INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'uploadpic', )
from __future__ import unicode_literals from django.db import models class IMG(models.Model): img = models.ImageField(upload_to='upload')
python manage.py migrate
python manage.py makemigrations uploadpic
python manage.py migrate
from django.shortcuts import render from uploadpic.models import IMG def upload(request): return render(request, 'uploadpic/upload.html') def show(request): new_img = IMG(img=request.FILES.get('img')) new_img.save() content = { 'aaa': new_img, } return render(request, 'uploadpic/show.html', content)
from django.conf.urls import include, url from django.contrib import admin from django.conf.urls.static import static from django.conf import settings from showpic.views import show from showpic.views import upload urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^upload', upload), url(r'^show', show), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media').replace('\\', '/')
<form method="POST" enctype="multipart/form-data" action="./../show"> {% csrf_token %} <input type="file" name="img"> <button type="submit">上傳</button> </form>
<img src='{{ aaa.img.url }}' />
python manage.py runserver
打開瀏覽器,輸入localhost:8000/upload,進入圖片上傳頁面,上傳後會顯示圖片.python