ImageField not working for Django version 2.0.4
ImageField not working for Django version 2.0.4
I am using Django version 2.0.4 but I am facing a problem with models.ImageField.
models.ImageField
Whenever I try to update an existing image with a new one, nothing happens. Also when I try to clear the image, nothing happens.
I have all the dependencies installed like Pillow.
I have declared my ImageField as usual like -
class Community(models.Model):
image = models.ImageField(
upload_to=upload_location,
null=True,
blank=True,
width_field="width_field",
height_field="height_field", help_text="A image representing the Community")
height_field = models.IntegerField(null=True, blank=True)
width_field = models.IntegerField(null=True, blank=True)
def __str__(self):
return str(self.id)
I have used ImageField before, but haven't ever faced such an issue ever. Is this a problem with the Django version? Should I consider upgrading my Django version?
Thanks in advance
Things I have tried -
I have tried a different database.
Tried upgrading the Pillow version
No no errors come
– Shahrukh Mohammad
Jul 3 at 6:06
Your image uploaded well?
– seuling
Jul 3 at 6:10
And are you using dev environment right now?
– seuling
Jul 3 at 6:11
Could you post your HTML file and view function ?
– Deadpool
Jul 3 at 6:34
2 Answers
2
You can upload or update an image in Django the following way:
models.py file
class ImageModel(models.Model):
image = models.FileField(upload_to="profile pics/", null=True, blank=True)
image.html file
<form method="post" enctype="multipart/form-data">
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
This is how I used to upload / update images in my project.
Hope things work well. Cheers!
I figured out what the problem was. I did implement the save method in the admin.py as
def save_model(self, request, obj, form, change):
if change:
obj.updated_by = request.user
else:
obj.created_by = request.user
obj.updated_by = request.user
obj.save()
which was causing the problem. I fixed it by calling the save_model of the super class like this -
def save_model(self, request, obj, form, change):
super().save_model(request, obj, form, change)
if change:
obj.updated_by = request.user
else:
obj.created_by = request.user
obj.updated_by = request.user
obj.save()
I know I should have called this function before, but it was a good learning for me to call it everytime necessary
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
I think it's not the problem from version. Do you get some error message?
– seuling
Jul 3 at 6:05