Reputation: 9925
What is the best practice to set up the upload path in django 1.4? I have a model like this
def upload_image(instance, filename):
return os.path.join(instance.slug, filename)
class Book(models.Model):
...
...
image = models.ImageField(upload_to=upload_image)
def admin_image(self):
return "<img src='%s' />" % self.image
....
with the settings.py
PROJECT_DIR = os.path.dirname(os.path.realpath(__file__))
ROOT_DIR = PROJECT_DIR.rsplit(os.sep, 1)[0]
MEDIA_ROOT = os.path.join(ROOT_DIR, 'books', 'static', 'books')
MEDIA_URL = '/media/'
STATIC_ROOT = ''
STATIC_URL = '/static/'
and admin.py like this
class BookAdmin(admin.ModelAdmin):
list_display = ('title', 'admin_image')
So, in the end, i got the image correctly saved into /root-of-project/books/static/books/programming-java/wall.jpg, however, the saved path in the database is "programming-java/wall.jpg" and i have to concat the prefix '/static/books/' everytime displaying image
Upvotes: 0
Views: 111
Reputation: 22449
Why would you concat/hardcode those lines in your templates? You can use the static tag for that purpose
{% load staticfiles %}
<img src="{% static "images/hi.jpg" %}" />
alias
{% load staticfiles %}
<img src="{% static object.image.url %}" />
and if you really must, you can add a method to your model which does it for you?
Upvotes: 1