Django - ImageField, upload, store and serve image in development server

随声附和 提交于 2019-12-10 22:13:45

问题


I'd like to have an ImageField in the admin form for my model (say, for an individual's profile). And I'd like to display this image in a view later on.

This is the model I have :

class Individual(models.Model):
    ind_name = models.CharField(max_length=100)
    ind_photo = models.ImageField(default="default.jpg")

    def __str__(self):
        return self.ind_name

This is what I have in the settings for my website :

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, "static")
MEDIA_URL = '/static/media/'
MEDIA_ROOT = os.path.join(BASE_DIR,"static/media")

These are the urls of my app:

urlpatterns = [
    url(r'^$', views.index, name="index")
]

I know how to use static files (e.g. CSS, Javascript), and to get them to work in both development and production. But I have no clue how to get images to work. I've read Managing static files and Deploying static files, but I still don't get it.

With the code above the image gets saved in the proper folder (i.e. /static/media at the level of my site). But I have no clue :

1) how to display it in a template,

2) whether it would be best to keep these images in my app's static folder,

3) and (if 2) whether I would need to run collectstatic every time someone uploads an image in the admin.

Sorry if I'm unclear, but this way more obscure than I thought it would be.


回答1:


In order for the image to be uploaded and served during development, I had to move the media folder out of the static folder (i.e. create a media folder at the root of my project's folder).

And in my main urls.py, I had to add :

from django.conf import settings
from django.conf.urls.static import static

if settings.DEBUG: 
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

as suggested by MicroPyramid.

To display it in a template, for a given Individual "somebody" (from a queryset), I use :

<img src="{{ somebody.ind_photo.url }}">



回答2:


It is good practice to separate both staticfiles and media files. Yes, you have to do collectstatic all the time when you upload if you store the images in static folder. We can get the image full url from the object like the following.

{{obj.ind_photo.url}}

For more info on files https://docs.djangoproject.com/en/1.10/topics/files/



来源:https://stackoverflow.com/questions/42069130/django-imagefield-upload-store-and-serve-image-in-development-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!