Django 实现图片上传和显示过程详解
第1章 新建工程和创建app
新建工程和创建app就不用贴出来了,我这里是测试图片上传的功能能否实现,所以项目都是新的,正常在以有的app下就可以
第2章 模型层:
2.1创建数据库
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初始化数据库:
(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章 数据校验模块:
数据需要校验的情况下,如果你不想校验,这个可以忽略
4.1在app下创建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>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。