如何在不使用 Django 表单的情况下在 Django 中上传图像

How to upload image in django without using django forms

型号

class Property(models.Model):
    property_id = models.BigAutoField(primary_key=True)
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    status = models.CharField(max_length=30, default='Public')
    title = models.CharField(max_length=30, default='')
    image1 = models.ImageField(upload_to="properties/images", default='', null=True)
    image2 = models.ImageField(upload_to="properties/images", default='', null=True)

    def save(self, *args, **kwargs):
        super().save(*args, **kwargs)

        if self.image1:
           img1 = Image.open(self.image1.path)
           if img1.height > 1500 or img1.width > 1500:
              output_size = (1500, 1500)
              img1.thumbnail(output_size)
              img1.save(self.image1.path)
    
       if self.image2:
           img2 = Image.open(self.image2.path)
           if img2.height > 1500 or img2.width > 1500:
              output_size = (1500, 1500)
              img2.thumbnail(output_size)
              img2.save(self.image2.path)

在这个模型中,我在 image1 和 image2 中加载图像。我使用 PIL 创建缩略图

查看

def post(self, request):
    status = request.POST.get('status')
    title = request.POST.get('title')
    image1 = request.FILES.get('image-1')
    image2 = request.FILES.get('image-2')

    if Property.objects.all():
        pid = Property.objects.all().last().property_id + 1
    else:
        pid = 0

    Property(property_id = pid, author = request.user, status = status, title = title).save()

    p = Property.objects.all().filter(property_id = pid)[0]

    if image1:
        p.image1 = image1
    
    if image2:
        p.image2 = image2

    p.save()

    return redirect('add_item')

HTML

<form method="POST" class="row gx-3 gy-4">
    {% csrf_token %}
    <!-- Status -->
    <label for="inputStatus">Status</label>
    <select name="status" id="inputStatus" required>
        <option disabled selected>Choose an option</option>
        {% for status in all_status %}
            <option value="Public">{{status}}</option>
         {% endfor %}
    </select>
    <!-- Title -->
    <label for="inputTitle">Title</label>
    <input name="title" type="text" required>
    <!-- Images -->
    <label for="inputTitle">Images</label>
    <input name="image-1" type="file">
    <input name="image-2" type="file">
</form>

有了这个代码,我可以添加 Product_id、作者、状态,但是当我在 django-admin 中打开这个模型时,image1 和 image2 没有上传到 properties/images 然后它看起来像一个空白图像字段

如果您提交文件,您需要指定如何使用 enctype="multipart/form-data" attribute [mozilla-dev]:

对这些文件进行编码
<form method="POST" class="row gx-3 gy-4" <strong>enctype="multipart/form-data"</strong>>
    {% csrf_token %}
    <!-- … -->
</form>