处理上传图像django admin python [英] handling uploading image django admin python

查看:109
本文介绍了处理上传图像django admin python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



我应该如何在settings.py中填充以下变量,让他们工作。

  MEDIA_ROOT = #root到我的项目

MEDIA_URL = #url

在models.py中我有

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

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

 MY_PROJECT_ADDRESS / static /图像/产品

您的帮助将不胜感激

解决方案

我建议您按照这个答案



需要最小的Django文件上传示例



,最好是将您的上传文件转到不同于静态的目录,但如果要将其上传到此目录,请执行以下操作:

  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无论你想要什么,当url被渲染它将是/media/imagename.jpg

和urls.py

  from django.conf.urls.static import static 
从django.conf导入设置


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


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

解决方案

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

这篇关于处理上传图像django admin python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆