Django 上传图片

源码:https://github.com/SingleDiego/Django-upload-picture




1.定义一个表单(form),来接收并处理上传的图片文件
from django import forms

class ProfileForm(forms.Form):
    name = forms.CharField(max_length = 100, label='名字:')
    picture = forms.ImageField(label='图片:') 




2.定义存储图片信息的模型
from django.db import models

# 用来保存上传图片相关信息的模型
class Profile(models.Model):
    name = models.CharField(max_length = 50)
    # upload_to 表示图像保存路径
    picture = models.ImageField(upload_to = 'test_pictures') 

    class Meta:
        db_table = "profile" 

    def __str__(self):
        return self.name

注意:要使用 ImageField 需要先安装第三方库 pillow。




3.设置文件存储路径

本例中,我们要把上传的图片保存在 myApp/static/uploads/test_pictures 的路径里。

在 settings 中设置以下属性:

# 静态文件的本地路径的绝对路径
STATIC_ROOT = os.path.join(BASE_DIR, 'myApp', 'static')
STATIC_URL = '/static/'

# 动态文件的本地路径的绝对路径
MEDIA_ROOT = os.path.join(STATIC_ROOT, "uploads")
MEDIA_URL = '/static/uploads/'

我们在上面 Model 中已经设置了:

upload_to = 'test_pictures'

表示上传的图片会保存到 MEDIA_ROOT 下的一个名为 test_pictures 的文件夹中。




4.在前端添加上传图片的接口

构建一个视图函数 index,用来展示上传图片使用的表单:

from django.shortcuts import render
from myApp.forms import ProfileForm # 上传图片的图表
from myApp.models import Profile # 保存上传图片相关信息的模型

def index(request):
    context = {}
    # 获取上传图片的表单,并加到 context 中,使得该表达能在前端展示
    form = ProfileForm
    context['form'] = form 
    return render(request, 'index.html', context)

编写前端:

<html>

<body>
    {# form 的请求方法为 post #}
    {# enctype 属性为 "multipart/form-data" 才能正确发送 #}
    {# 发送到的网址 save_profile 将在下面 url 中定义 #}
    <form enctype="multipart/form-data" action="{% url "save_profile" %}" method="POST">

    {# csrf许可标签,需要该标签才能发送请求 #}
    {% csrf_token %}

    {# 上传图片的表单 #}
    {% for field in form %}
        {{ field.label }}
        {{ field }}
    {% endfor %}

    <br><br>

    {# 按钮,type 属性需设为 "submit" #}
    <button type="submit" value="Login">上传</button>

    </form>
</body>

</html>

注意:请求方法需为 POST,并且发送请求的 form 拥有 enctype="multipart/form-data" 属性时,才能正确上传。

也可以不使用 Django 的表单,用 html 语言来实现上传:

<html>

<body>

    <form enctype="multipart/form-data" action="{% url "save_profile" %}" method="POST">

    {% csrf_token %}

    <input type="text" placeholder="名字" name="name" />
    <br><br>
    <input type="file" placeholder="图片" name="picture" />
    <br><br>
    <button type="submit" value="Login">上传</button>
    </form>
</body>

</html>




5.处理接收到的图片并存储
from django.shortcuts import render, redirect
from myApp.forms import ProfileForm # 上传图片的图表
from myApp.models import Profile # 保存上传图片相关信息的模型

def save_profile(request):

    if request.method == "POST":
        # 接收 post 方法传回后端的数据
        MyProfileForm = ProfileForm(request.POST, request.FILES)
        # 检验表单是否通过校验
        if MyProfileForm.is_valid():
            # 构造一个 Profile 实例
            profile = Profile()
            # 获取name
            profile.name = MyProfileForm.cleaned_data["name"]
            # 获取图片
            profile.picture = MyProfileForm.cleaned_data["picture"]
            # 保存
            profile.save()

        else:
            return redirect(to='index')

        return redirect(to='index')




6.设置 url
urlpatterns = [
    …………
    # 上传并保存图片的 url
    url(r'^save_profile/', save_profile, name='save_profile'),

    # 展示表单的 url
    url(r'^index/', index_form, name='index'),
]
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容