[Solved]-Django ImageField default

15👍

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?

👤ryan

Leave a comment