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.
Answers:
You seem to be missing enctype="multipart/form-data"
in your form tag. It is required when dealing with uploaded files.
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
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.
You seem to be missing enctype="multipart/form-data"
in your form tag. It is required when dealing with uploaded files.
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