0

I made an HTML form which uploaded the image and that image I have to use in Django Views to perform something of that image, how can I do?

1 Answers1

0

You have to add enctype="multipart/form-data" in your form tag in HTML so that the image file can be submitted to server. in your view you can write something like this .

def view_name(request):

    if request.method == 'POST':
        form = YourForm(request.POST, request.FILES)
        if form.is_valid():
            #  do something with files
            form.save()
            return redirect('some-view')
        else:
            form = YourForm()
            context= {'form' : form}
            return render(request,'your_template.html', context)
    else:
        form = YourForm()
        context= {'form' : form}
        return render(request,'your_template.html', context)
Subham
  • 671
  • 9
  • 23
  • Thanks, Can you explain enctype="multipart/form-data" and form = YourForm(request.POST, request.FILES) , YourForm ? – Muhammad Parwej Nov 07 '19 at 17:02
  • YourForm is the name of form class that you defined in your forms.py and `form enctype="multipart/form-data"` is used to encode your data in post method for more you can visit https://stackoverflow.com/questions/4526273/what-does-enctype-multipart-form-data-mean – Subham Nov 07 '19 at 17:44
  • bro, Directly I want to fetch the image in Django views and perform task and show in the screen (result.html), I do not want to save it in DataBase, That image will be uploaded through the HTML page – Muhammad Parwej Nov 07 '19 at 18:34
  • You have to store on the server file system and save the file path to the database. then, you can do any operation on image nad show to the user otherwise without storing on the server I don't know how to do it. you can check if you want to store in the cookie. https://stackoverflow.com/questions/11130171/store-a-picture-in-a-cookie – Subham Nov 08 '19 at 05:27