Django ImageField Is Empty
I am trying to create a form that uses ajax to create a new user. All the other fields work, besides the ImageField. I don't get a error when submitting, but the image will still n
Solution 1:
I suggest using the following method:
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
gender = models.CharField(max_length=6, blank=False)
dateOfBirth = models.DateField(null=True, blank=False)
bio = models.TextField(max_length=500, blank=True)
profileImage = models.ImageField(upload_to="UploadTo('user_photo')", blank=True, null=True)
hobby = models.ManyToManyField(Hobby, blank=False)
Where UploadTo
is a class for saving your photos under a directory called user_photo
in your media folder.
from django.utils.deconstruct import deconstructible
from uuid import uuid4
@deconstructible
class UploadTo(object):
def __init__(self, path):
self.sub_path = path
def __call__(self, instance, filename):
ext = filename.split('.')[-1]
# get filename
if instance.pk:
filename = '{}.{}'.format(instance.pk, ext)
else:
# set filename as random string
filename = '{}.{}'.format(uuid4().hex, ext)
# return the whole path to the file
return os.path.join(self.sub_path, filename)
This class will set properly the path to be used so that your photo can be found, because the problem is in the path you are passing to upload_to
.
Disclaimer: the code above is not mine, but worked well for me.
Solution 2:
I would comment, but I can't. How does the post data look like and is the image actually in there? You might wanna remove blank=True and null=True from the ImageField for testing purposes. Django should complain about the image not being there or something.
if image.is_valid()
might return false and therefore not save the image
Post a Comment for "Django ImageField Is Empty"