Django: Failed to load image

I am trying to load images from my models using.

forms fields

image_id = forms.CharField(widget=forms.HiddenInput(), required=False)
image = forms.FileField(label = 'Select a Profile Image')

      

usefulness

def get_user(self):
    users = User.objects.all()
    data ={'users':users}
    return data

      

view

template_name= '/profile.html'
def get(self,request, *args, **kwargs):
    data = self.get_context_data(*args, **kwargs)
    data.update({'user_detail':self.get_user(request.user)})
    return self.render_to_response(data)

      

Settings

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media').replace('\\', '/')

      

Templates

<center>
<img src="{{user_detail.profile_image.image}}" height="150px" width="150px">
</center>

      

I am not getting the image on the page.

+3


source to share


1 answer


Both media (user uploaded) and static files (images, css, js used by your site) must be server using a web server like Apache, Nginx, etc.

Django does no magic here, and it is your responsibility to properly configure your web server to serve these files.

For example, let's say you set up Django like this:

STATIC_URL = '/static'
STATIC_ROOT = '/var/www/mywebsite/static'

MEDIA_URL = '/media'
MEDIA_ROOT = '/var/www/mywebsite/media'

      

You need to configure your web server to serve files from these * _ROOT directories in the URLs identified by the * _URL variables. In Apache, you can use two directives like these:



Alias /media /var/www/mywebsite/media
Alias /static /var/www/mywebsite/static

      

Without a web server to handle media and static files, there is no way for the browser to access those files.

Also I suggest using ImageField instead of FileField if the file to upload is an image.

Then in the template, you can write something like this to have the full image url:

<img src="{{user_detail.profile_image.image.url}}" height="150px" width="150px">

      

0


source







All Articles