无法将图像上传到Django Admin

时间:2020-06-20 12:32:33

标签: python django django-models django-admin

我正在从事电子商务项目,而我一直坚持下去。管理员每次添加新产品时,也应添加与该产品相关的图片。所以我用ImageField添加了该列,但是我一次又一次地出错。这是我的模型代码

// c++ struct

typedef struct dll_info_t
{
   char version[32];
   char r_type[128];
   char b_date[32];
   char c_list[32];
   char build[32];
}dll_info_t;

LIBEX_EXPORT int LIB_API Dll_get_lib_info(dll_info_t* info);

// Delphi Converted

dll_info_t = record
 version:AnsiChar;
 r_type:AnsiChar;
 b_date:AnsiChar;
 c_list:AnsiChar;
 build:AnsiChar;
end;
        
Dll_get_lib_info: Function (info : dll_info_t) : Integer; stdcall;

var
  hHandle:THandle;
begin
  hHandle := LoadLibrary(Dl_path);
    @Dll_get_lib_info:=GetProcAddress(hHandle, PChar('Dll_get_lib_info'));

    if Assigned(Dll_get_lib_info) then begin
     Dll_get_lib_info(info);
     ShowMessage(info.version); // <- I Get Empty Output
     ShowMessage(info.release_type); // <- I Get Empty Output
     ShowMessage(info.build_date); // <- I Get Empty Output
     ShowMessage(info.change_list); // <- I Get Empty Output
    end;

end;

和admin.py

class Product(models.Model):
    product_id = models.IntegerField(primary_key=True)
    name = models.CharField(max_length=100, blank=True, null=True)
    image = models.ImageField(db_column='image' , blank=True, null=True)
    info = models.CharField(max_length=500, blank=True, null=True)
    
    def image_tag(self):
        if self.image:
            return mark_safe('<img src="%s"/>' % self.image.url)
        else:
            return 'No Image Found'
    image_tag.short_description = 'Image'

但是每次我收到此错误

class ProductAdmin(admin.ModelAdmin):
    list_display = ('product_id', 'name','image_tag', 'info')
    readonly_fields = ('image',)

admin.site.register(Product, ProductAdmin)

我尝试使用转义,但它仍然不显示图像。我正在使用MySQL现有数据库。我真的可以使用帮助。谢谢

1 个答案:

答案 0 :(得分:0)

当前,您将图像以字节为单位存储在数据库中,Django不建议这样做,而是应首先指定MEDIA_ROOT,这是用于保存图像的文件夹,仅URL将被保存在数据库中。文件[SOURCE]

我假设您已经设置了MEDIA设置并安装了Pillow。 您的ImageField看起来像

# No need to specify db_column as Django already stores by default field's name.
image = models.ImageField(upload_to='users/%Y/%m/%d/', blank=True, null=True)

现在,您可以在模板中获取图像了,

<img src="http://127.0.0.1:8000/media/{{ profile.photo }}" id='profile-photo'>
相关问题