I am trying to upload an image from input field but when I check from database (using Value in Editor), it shows a text which is a file name. I’m new to uploading image, so I’m not sure what’s missing in my code. I added media root on settings.py and urls.py. Here is my code.
models.py
class ImageUpload(models.Model):
idupload = models.AutoField(db_column='idupload', primary_key=True)
image = models.ImageField(db_column='image', upload_to="media/", null=True)
description = models.CharField(db_column='description', max_length=50, null=True)
class Meta:
managed = True
db_table = 'image_upload'
upload.html
<form method="post" action="" enctype="multipart/form-data" >
{% csrf_token %}
<div class="form-group">
<label>Upload File</label>
<input class="form-control" name="image" type="file" required>
</div>
<div class="form-group">
<label>Description</label>
<input class="form-control" name="description" required>
</div>
<button type="submit" name="upload" class="btn btn-gray-800 mt-2 animate-up-
</form>
views.py
def uploadImage(request):
if request.method == 'GET':
return render(request, 'upload.html')
if request.method == 'POST':
image = request.FILES.get('image')
description = request.POST.get('description')
ImageUpload.objects.create(image=image, description=description)
return redirect('/images/')
I tried above code but I kept on getting nothing.
2
Answers
So this is how I did it.
And here is how I view the images in html.
you can use
CreateView
this will save the Image into your media folder.in urls.py
tempates
myapp/imageupload_form.html
: