How to display a image which is generated in the backend with Django

48 views
Skip to first unread message

rylanlee

unread,
Nov 22, 2015, 11:23:55 AM11/22/15
to Django users

I am new to django and I am confused with the image display problem. Now I have a image of word-cloud generated in the backend(let's say, topicWords.py) and I don't know hot to deal with it. (1) How can I store it in the image field of model UserProfile? In the models.py, I have:

class UserProfile(models.Model):
user = models.OneToOneField(User)
tagcloud = models.ImageField(upload_to ='rap_song/raptle/pic/')

Is it right to directly do like:

user.userprofile.tagcloud = wc #wc is the image generated

(2) What should the setting of MEDIA_ROOT and MEDIA_URL be?

(3) How should I display it in the .html?

<img src = "???">

Thank you very much!

Aaron C. de Bruyn

unread,
Nov 22, 2015, 12:25:06 PM11/22/15
to django...@googlegroups.com
If I recall correctly, the 'wc' object would need to be a file object.  You could assign it similar to this:

from django.core.files import File
wc = File(open('/path/to/image', 'r'))
user.userprofile.tagcloud = wc
user.userprofile.save()

If the 'wc' variable returned by your program is already a file-like object, you don't have to perform the 'open' step.

MEDIA_ROOT and MEDIA_URL can be whatever you want.  The ROOT is where the files will be stored on disk, and the URL is where they should be accessible via URL.  For example, most of my projects have:

MEDIA_URL = '/media/'
MEDIA_ROOT = 'media'

To display it in a template, try something like:
<img src="{{ MEDIA_URL }}/user.userprofile.tagcloud" />

It's been a while since I've used ImageFields, hopefully someone can correct me if I missed something.

-A


--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/53934b58-f17b-469a-9765-981612d9ae29%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

rylanlee

unread,
Nov 22, 2015, 12:33:17 PM11/22/15
to Django users
Thanks for your reply! But what if the wc is a image object? The image is generated directly and I can not call it from any folder. 

Best regards,
Rylan

Aaron C. de Bruyn於 2015年11月23日星期一 UTC+8上午1時25分06秒寫道:
Reply all
Reply to author
Forward
0 new messages