[英]How to link to user-uploaded profile pictures (ImageField) in Django templates?
[英]How to “link” already uploaded images to ImageField in Django?
我有這樣的模型:
class Symbol(models.Model):
slug = models.SlugField(unique=True) #uniqe
name = models.CharField(max_length=255, unique=True)
imgslug = models.CharField(unique=False, max_length=255, blank=True) #uniqe
def __str__(self):
return self.name
class Platform(models.Model):
name = models.CharField(max_length=50, unique=True)
def __str__(self):
return self.name
class PlatformImages(models.Model):
symbol_id = models.ForeignKey('Symbol', on_delete=models.CASCADE,)
platform_id = models.ForeignKey('Platform', on_delete=models.PROTECT,)
class Meta:
indexes = [
models.Index(fields=['symbol_id', 'symbol_id']),
]
constraints = [
models.UniqueConstraint(fields=['symbol_id', 'platform_id'], name='unique_symbol_img_per_platform')
]
def __str__(self):
return str(self.platform_id)
def get_platform_name(self):
return self.platform_id
我在媒體文件夾中有每個平台的文件夾,例如:media/apple/、media/google/、media/twitter/等。
在每個文件夾內有大約 1000-3000 張圖像,幾乎每個符號都被命名為“imgslug”。 我已經批量上傳了它們。
我在模板中使用它來顯示每個平台符號的所有可用圖像:
{% for platform in platforms %}
<img src="{{ MEDIA_PREFIX }}{{platform}}/{{symbol.imgslug}}" >
<h2 class="">{{platform|title}}</h2>
{% endfor %}
問題是現在我需要通過管理工具編輯/上傳新圖像。 我將此代碼添加到 admin.py 以編輯圖像到平台的映射:
class PlatformInline(admin.TabularInline):
model = PlatformImages
class SymbolAdmin(admin.ModelAdmin):
inlines = [
PlatformInline,
]
現在我想將ImageField添加到PlatformImages Model,但我需要:
挖掘 web 后,我得出以下解決方案:
在添加到 models.py 的相應文件夾中為符號保存每個唯一平台的每個圖像:
class Platform(models.Model): name = models.CharField(max_length=50, unique=True) folder = models.SlugField(unique=True, null=True, blank=True) def platform_directory_path(instance, filename): return '{0}/{1}'.format(instance.platform_id.folder, filename) class PlatformImages(models.Model): symbol_id = models.ForeignKey('Symbol', on_delete=models.CASCADE,) platform_id = models.ForeignKey('Platform', on_delete=models.PROTECT,) image = models.ImageField(upload_to=platform_directory_path, null=True, blank=True)
2) 將已上傳的圖片鏈接到 ImageField,打開 shell
python3 manage.py shell
並執行腳本:
from django.db import models
images = PlatformImages.objects.all()
for image in images:
platform = image.platform_id.name
symbol = image.symbol_id.imgslug
imagePath = str(platform +'/'+symbol)
print (str(image.id) + " : " + imagePath)
image.image = imagePath
image.save()
是什么幫助我找到了解決方案:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.