python Django的实现图片的上传,保存和展示

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python Django的实现图片的上传,保存和展示相关的知识,希望对你有一定的参考价值。

def upload_image_path(instance, filename):
    '''
    图片的保存是自动发生的,我们只需指定保存
    在settings.MEDIA_ROOT中的相对路径即可
    '''
    new_filename = random.randint(1,3910209312)
    # 原来的name就不要了,对图片重命名
    name, ext = get_filename_ext(filename)
    final_filename = f"{new_filename}{ext}"
    return f"products/{new_filename}/{final_filename}"

class Product(models.Model):
    title       = models.CharField(max_length=120)
    description = models.TextField()
    price       = models.DecimalField(decimal_places=2, max_digits=20, default=39.99)
    image       = models.ImageField(upload_to=upload_image_path, null=True, blank=True)

'''
{{ object.title }} <br/>
{{ object.description }} <br/>
{{ object.image }} ==> products/2969889474/2969889474.jpg
image字段自带url方法
{{ object.image.url }} ==> /media/products/2969889474/2969889474.jpg
<img src='{{ object.image.url }}' class='img-fluid' />
'''
In [6]: p.image
Out[6]: <ImageFieldFile: products/2969889474/2969889474.jpg>

In [7]: p.image.url
Out[7]: '/media/products/2969889474/2969889474.jpg'

In [8]: p.title
Out[8]: 'Hat'
class Upload(models.Model):
    thing = models.ForeignKey(Thing, related_name='uploads')
    image = models.ImageField(upload_to=get_image_path)

    def get_delete_url(self):
        return reverse('delete_upload', kwargs={'id': self.id})

    def save(self, *args, **kwargs):
        super().save(*args, **kwargs)
        if self.image:
            # 直接修改保存后的存储路径中的图片尺寸
            image = Image.open(self.image)
            i_width, i_height = image.size
            max_size = (300, 300)
            if i_width > 300:
                image.thumbnail(max_size, Image.ANTIALIAS)
                image.save(self.image.path)
# Uploading files in the templates
'''
    <h1>Edit {{ thing.name }}'s Images</h1>
    <h2>Uploaded images</h2>

    {% for upload in uploads %}
      <img src="{{ upload.image.url }}" alt="" />
      <a href="{{ upload.get_delete_url }}">Delete</a>
    {% endfor %}

    <h2>Upload a new image</h2>
    <form role="form" action="" method="post" enctype="multipart/form-data">
        {% csrf_token %}
        {{ form.as_p }}
        <input type="submit" value="Submit" />
    </form>
'''


@login_required
def edit_thing_uploads(request, slug):
    thing = get_object_or_404(Thing, slug=slug)
    if thing.user != request.user:
        raise Http404
    form_class = ThingUploadForm
    if request.method == 'POST':
        # 这一行是关键,文件和图片都需要额外传参
        form = form_class(data=request.POST, files=request.FILES)
        if form.is_valid():
            # Instead of just saving the form, 
            # we’ve created a new object from the form’s uploaded image.
            # Upload.objects.create(image=form.cleaned_data['image'], thing=thing)
            obj = form.save(commit=False)
            obj.thing = thing
            obj.save()
            return redirect('edit_thing_uploads', slug=thing.slug)
    else:
        form = form_class()
        uploads = thing.uploads.all()
        return render(request, 'things/edit_thing_uploads.html', {
            'thing':thing,
            'form':form,
            'uploads':uploads,
        })

以上是关于python Django的实现图片的上传,保存和展示的主要内容,如果未能解决你的问题,请参考以下文章

python测试开发django-47.xadmin上传图片和文件

Django_上传图片和模版获取图片

[Python] Django框架入门5——静态文件中间件上传图片和分页

django 配置上传图片和文件

Django入门手册04 上传图片并保存路径到数据库展示图片

django python上传文件有中文名称报错