Search code examples
pythondjangodjango-modelsdjango-viewsdjango-forms

How to upload image in django without using django forms


Model

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)

In this model i to uoload Images in image1 and image2. I used PIL to create thumbnail

View

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>

With this is code i can add Product_id, author, status but image1 and image2 is not uploading to properties/images when i open to this model in django-admin then its look like a blank image field


Solution

  • If you submit files you need to specify how to encode these with the enctype="multipart/form-data" attribute [mozilla-dev]:

    <form method="POST" class="row gx-3 gy-4" enctype="multipart/form-data">
        {% csrf_token %}
        <!-- … -->
    </form>