我需要在帖子中上传数量不确定的图片,目前我只能上传一张照片进行发布 如何在单个帖子中上传多张图片? 我正在附加应用程序的代码。
models.py
class Casa(models.Model):
nome_casa = models.CharField(max_length=80)
descrizione = models.TextField()
logo_casa = models.ImageField(blank=True, null=True)
def __str__(self):
return self.nome_casa
def get_absolute_url(self):
return reverse("visualizza_casa", kwargs={"pk" : self.pk})
class Meta:
verbose_name = "Casa"
verbose_name_plural = "Case"
views.py
from django.shortcuts import render, get_object_or_404
from django.views.generic.edit import CreateView
from .models import Casa
from .mixins import StaffMixin
class CreaCasa(StaffMixin, CreateView):
model = Casa
fields = '__all__'
template_name = "inserzioni/crea_casa.html"
success_url = "/"
def visualizzaCasa(request, pk):
casa = get_object_or_404(Casa, pk=pk)
context = {"casa" : casa}
return render(request, "inserzioni/visualizza_casa.html", context)
答案 0 :(得分:0)
正如我所看到的,您有模型Casa
,现在它只有一个ImageField
(logo_casa
),但是您想向其添加其他图像。
最简单的方法是创建另一个模型(例如CasaImage
)并向其中添加ImageField
。示例:
# models.py
class Casa(models.Model):
nome_casa = models.CharField(max_length=80)
descrizione = models.TextField()
logo_casa = models.ImageField(blank=True, null=True)
def __str__(self):
return self.nome_casa
def get_absolute_url(self):
return reverse("visualizza_casa", kwargs={"pk" : self.pk})
class Meta:
verbose_name = "Casa"
verbose_name_plural = "Case"
class CasaImage(models.Model):
casa = models.ForeignKey(Casa, on_delete=models.CASCADE)
image = models.ImageField()
请注意,我离开了logo_casa
字段以将徽标与其他Casa
图像区分开。 CasaImage
具有ForeignKey
字段,该字段表示多对一数据库关系(您可以在此处https://docs.djangoproject.com/en/2.2/topics/db/examples/many_to_one/中阅读更多信息)。参数on_delete=models.CASCADE
意味着当我们删除Casa
实例时,所有相关的CasaImages
都将被自动删除。