处理上传图片django admin python

时间:2014-03-21 22:35:03

标签: python django django-admin image-uploading

我正在使用Windows上的Python Django开发一个应用程序我正在尝试将图像上传字段添加到我的一个类中但我得到错误,我必须提到我需要给一个相对路径到settings.py所以我可以轻松地将我的代码迁移到另一个平台

我应该如何填写settings.py中的以下变量以使其正常工作

MEDIA_ROOT = #root to my project

MEDIA_URL = #url 

在models.py我有

class ProdcutImage(models.Model):
    product = models.ForeignKey(Product)
   image = models.ImageField(upload_to = "/products" )

我需要将图像上传到此文件夹中:

"MY_PROJECT_ADDRESS/static/images/products"

您的帮助将不胜感激

1 个答案:

答案 0 :(得分:6)

我建议你按照这个答案

Need a minimal Django file upload example

并且最好将上传文件转到与静态不同的目录,但是如果要将其上传到此目录:

class ProdcutImage(models.Model):
    product = models.ForeignKey(Product)
   image = models.ImageField(upload_to = "static/images/products" )

settings.py

import os
PROJECT_ROOT = os.path.realpath(os.path.dirname(__file__))

MEDIA_ROOT = PROJECT_ROOT + '/static/images/products/'
MEDIA_URL = '/media/'  #put whatever you want that when url is rendered it will be /media/imagename.jpg

和urls.py

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


+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)  #at the end