handling uploading image django admin python

北战南征 提交于 2020-01-02 09:39:52

问题


I am developing an application with Python Django on Windows I'm trying to add an image upload field to one of my class but I get errors, I have to mention that I need to give a relative path to the settings.py so I can easily migrate my code to another platform

how should I fill the following variables in settings.py to get them work

MEDIA_ROOT = #root to my project

MEDIA_URL = #url 

And in the models.py I have

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

I need the images to be uploaded in this folder :

"MY_PROJECT_ADDRESS/static/images/products"

Your helps will be appreciated


回答1:


I suggest you to follow this answer

Need a minimal Django file upload example

and it is better that your upload file go to a different directory than static but if you want to upload it to this directory:

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

and in 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


来源:https://stackoverflow.com/questions/22570723/handling-uploading-image-django-admin-python

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