How to save user input image in ImageField of Django Model

Question:

I’m trying to save a user image in my database. Below is my input form:

<form method="POST" action="/savedata/">
{% csrf_token %}
<input id="file-upload" type="file"  accept="image/*" name='profileimg' />
<input type="submit" value="upload">
</form>

How could I save the selected image in the database using form submit

My model class:

class usertab(models.Model):
    img = models.ImageField(upload_to='user_img')

I am able to save an image using superuser but I need to save this using submission form, how could I possibly do it?

many thanks in advance.

Asked By: Hemant Prajapat

||

Answers:

You seem to be missing enctype="multipart/form-data" in your form tag. It is required when dealing with uploaded files.

Answered By: mariodev

for submit file in django you should use enctype="multipart/form-data" property in your form and get it in your view with myfile = request.FILES['myfile']

  <form method="post" enctype="multipart/form-data">
    {% csrf_token %}
   <input type="file" name="myfile">
   <button type="submit">Upload</button>
 </form>

views:

def simple_upload(request):
   if request.method == 'POST' and request.FILES['myfile']:
      myfile = request.FILES['myfile']
      # statements

Ref

Answered By: Khashayar Ghamati
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.