Django ImageField default

Mihai Zamfir picture Mihai Zamfir · Mar 22, 2014 · Viewed 16.2k times · Source

models.py:

class UserProfile(models.Model):

    photo = models.ImageField(upload_to = get_upload_file_name,
                              storage = OverwriteStorage(),
                              default = os.path.join(settings.STATIC_ROOT,'images','generic_profile_photo.jpg'),
                              height_field = 'photo_height',
                              width_field = 'photo_width')
    photo_height = models.PositiveIntegerField(blank = True, default = 0)
    photo_width = models.PositiveIntegerField(blank = True, default = 0)

views.py:

def EditProfile(request):

    register_generator()
    source_file = UserProfile.objects.get(user = request.user).photo

    args = {}
    args.update(csrf(request))
    args.update({'source_file' : source_file})

somewhere in my template:

{% generateimage 'user_profile:thumbnail' source=source_file %}

I receive an error: UserProfile matching query does not exist.

at this line:

source_file = UserProfile.objects.get(user = request.user).photo

The problem is that the default atribute of ImageField is not working. Thus, the object is not created inside my model. How to use this atribute properly? If I ommit this atribute, the object is created with no errors. Do I need to pass the absolute or relative path? I am using django-imagekit to resize the image before dispalying it: http://django-imagekit.readthedocs.org/en/latest/

Answer

ryan picture ryan · Mar 22, 2014

If you don't define the default attribute, does image uploading work successfully? When I implemented an ImageField in my own django project, I didn't use the default attribute. Instead I wrote this method to get the path to the default image:

def image_url(self):
"""
Returns the URL of the image associated with this Object.
If an image hasn't been uploaded yet, it returns a stock image

:returns: str -- the image url

"""
    if self.image and hasattr(self.image, 'url'):
        return self.image.url
    else:
        return '/static/images/sample.jpg'

Then in the template, display the image with:

<img src="{{ MyObject.image_url }}" alt="MyObject's Image">

EDIT: Simple example

In views.py

def ExampleView(request):
    profile = UserProfile.objects.get(user = request.user)
    return render(request, 'ExampleTemplate.html', { 'MyObject' : profile } )

Then in the template, include the code

<img src="{{ MyObject.image_url }}" alt="MyObject's Image">

would display the image.

Also for the error 'UserProfile matching query does not exist.' I assumee you have defined a foreign key relationship to the User model somewhere in your UserProfile model, correct?