Tanish Surana
Tanish Surana

Reputation: 125

How to store an image without using django forms

html form:

<form action = "{% url 'newcomplaint' %}" class = 'newc' method = "post" enctype = "multipart/form-data" >
    { % csrf_token % }

    <div class = "form-group" >
    <label for = "fileToUpload" > Add an image(optional) < /label >
    <input type = "file" name = "fileToUpload" id = "fileToUpload" >
    </div >

    <button type = "submit" class = "btn btn-dark bb" > Post New Complaint < /button >
</form >

views.py: Here I am getting MultiValueDictKeyError at /hood/new

def newcomplaint(request):
    if request.method == "POST":
        # I dont know how to store a image here
        image = request.FILES['fileToupload']
        #print(image)
        return HttpResponse('works')

model.py

from django.db import models
from django.core.exceptions import ValidationError 
from django.contrib.auth.models import User

class Complain(models.Model):
    image = models.ImageField(upload_to='images/', blank=True)
    

All the solutions that I see are done using django forms, I want to avoid that as I have made a bigger form with image field plus some other input (and added styling and Js check for validation).

So how to retrieve a file from a form and store it in django.

Upvotes: 0

Views: 454

Answers (3)

Tanish Surana
Tanish Surana

Reputation: 125

I had a typo, also found a solution how to store a file/image in django without forms

my working code: views.py

def newcomplaint(request):
if request.method == "POST":
    newcomplaint = Complain.objects.create(
        user=request.user,
        title=request.POST['title'],
        content = request.POST['content'],
        ran = request.POST['range'],
        lati = request.POST['lati'],
        longi = request.POST['longi'],
        )

    if len(request.FILES) == 0:
        print('no files')
    else: 
        _, file = request.FILES.popitem()
        file = file[0]
        newcomplaint.image = file
        newcomplaint.save()
    


    return HttpResponse('works')

Upvotes: 1

SAI SANTOSH CHIRAG
SAI SANTOSH CHIRAG

Reputation: 2084

There is a typo. You have written fileToupload. It should be fileToUpload

Upvotes: 0

mhawke
mhawke

Reputation: 87054

Your code expects fileToupload to be the key, however, your form uses fileToUpload.

Upvotes: 1

Related Questions