首页 > 解决方案 > 如何以编程方式在 django oscar 中添加产品图片?

问题描述

我目前正在以编程方式将产品导入我的产品目录,但是,我很难为每个产品上传图片。这是我的代码的样子:

# frobshop/custom_utils/product_importer.py

from oscar.apps.catalogue.models import Product
...

for product in my_product_import_list:
    ...
    product_entry = Product()
    product_entry.title = my_product_title
    product_entry.product_class = my_product_class
    product_entry.category = my_category
    product_entry.primary_image = "product_images/my_product_filename.jpg"
    product_entry.save()

当我使用开发服务器检查时,产品标题和产品类别等详细信息已成功保存,但是我不确定如何为每个产品设置图像。

整个product_images文件夹最初位于我的media目录之外,但由于我没有得到任何结果,我将图像的整个文件夹复制粘贴到media目录中,但仍然没有结果。我假设跳过了很多步骤,并且可能有关于如何在媒体目录中排列图像的约定。但是,我不确定在哪里可以找到这些步骤和约定。

settings.py是处理我安装的应用程序、媒体目录和静态文件的文件部分:

# frobshop/frobshop/settings.py

...

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',

    'django.contrib.sites',

    'django.contrib.messages',
    'django.contrib.staticfiles',

    'django.contrib.flatpages',

    'compressor',
    'widget_tweaks',
] + get_core_apps(['custom_apps.shipping', 'custom_apps.payment', 'custom_apps.checkout'])

...


STATIC_ROOT = 'static'
STATIC_URL = '/static/'
MEDIA_ROOT = 'media'
MEDIA_URL = '/media/'

为了更清楚,这是我的urls.py

from django.contrib import admin
from django.urls import path
from django.conf.urls import include, url
from oscar.app import application
from django.conf import settings
from django.conf.urls.static import static


urlpatterns = [
    url(r'^i18n/', include('django.conf.urls.i18n')),
    path('admin/', admin.site.urls),
    url(r'', application.urls),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

标签: pythondjangoimagedjango-oscar

解决方案


我认为你可以使用类来做到这一点File

from django.core.files import File

for product in my_product_import_list:
    ...
    product_entry = Product()
    product_entry.title = my_product_title
    product_entry.product_class = my_product_class
    product_entry.category = my_category
    image = File(open("product_images/my_product_filename.jpg", 'rb'))
    product_entry.primary_image = image
    product_entry.save()

更新

可能你应该OSCAR_MISSING_IMAGE_URL在设置中使用:

OSCAR_MISSING_IMAGE_URL = "product_images/my_product_filename.jpg"  # relative path from media root

或者,您可以使用ProductImage,如下所示:

    from oscar.apps.catalogue.models import ProductImage

    product_entry = Product()
    product_entry.title = my_product_title
    product_entry.product_class = my_product_class
    product_entry.category = my_category
    product_entry.save()
    product_image = ProductImage()
    image = File(open("product_images/my_product_filename.jpg", 'rb'))
    product_image.original = image
    product_image.caption = "Some Caption"
    product_image.product = product_entry
    product_image.save()

AsProductImage与 Model 有 ForignKey 关系Product,并且primary_image是模型中的一个方法Product,它从 ProductImage 模型中获取图像,并返回第一个(按该字段中的字段ProductImage排序的对象)display_order


推荐阅读