如何在Django中提供用户上传的文件?

时间:2022-12-26 10:36:46

I'm writing a Django app in which the users can upload images, and I'm not sure how to serve them. I can see two ways:

我正在编写一个Django应用程序,用户可以上传图像,我不知道如何为它们提供服务。我可以看到两种方式:

1- upload them as static files: upload them in the static folder in my project's directory, and then run python manage.py collectstatic, but I don't know how to run this command automatically every time a file is uploaded, and this seems to be a lot of processing because every time the server will delete and reload everything in my static app.

1-将它们作为静态文件上传:将它们上传到我项目目录下的静态文件夹中,然后运行python manage.py collectstatic,但我不知道每次上传文件时如何自动运行此命令,这似乎因为每次服务器都会删除并重新加载静态应用程序中的所有内容,所以需要进行大量处理。

2- use django.views.static.serve in my urls.py:

2-在我的urls.py中使用django.views.static.serve:

url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {
        'document_root': settings.MEDIA_ROOT,
    }),

but the doc does not recommend it for production.

但是doc不推荐它用于生产。

What's the recommended way to serve user-uploaded files?

提供用户上传文件的推荐方法是什么?

1 个解决方案

#1


2  

Your uploaded files go in MEDIA_ROOT and can be served using MEDIA_ROOT. You need to set these parameters in settings.py.

您上传的文件在MEDIA_ROOT中,可以使用MEDIA_ROOT提供。您需要在settings.py中设置这些参数。

Your development you can serve them though django dev server, but you can configure it to serve from apache or other server.

您可以通过django dev服务器为您的开发提供服务,但您可以将其配置为从apache或其他服务器提供服务。

Refer Django managing stored files

请参阅Django管理存储的文件

#1


2  

Your uploaded files go in MEDIA_ROOT and can be served using MEDIA_ROOT. You need to set these parameters in settings.py.

您上传的文件在MEDIA_ROOT中,可以使用MEDIA_ROOT提供。您需要在settings.py中设置这些参数。

Your development you can serve them though django dev server, but you can configure it to serve from apache or other server.

您可以通过django dev服务器为您的开发提供服务,但您可以将其配置为从apache或其他服务器提供服务。

Refer Django managing stored files

请参阅Django管理存储的文件