【问题标题】:How to add multiple input from one field in django model如何在 django 模型中从一个字段添加多个输入
【发布时间】:2019-09-20 09:14:53
【问题描述】:

我有这个 models.py 代码,我想从单个字段中获取多个值/文件,而不是为图像创建另一个表。

目前我只是重复这些字段

class contentimage(models.Model):
content = models.ForeignKey(element, on_delete=models.CASCADE)
title = models.CharField(max_length=200)

titleimg1 = models.CharField(max_length=200)
image1 = models.ImageField(blank=True, upload_to='media/')
img1description = models.TextField()

titleimg2 = models.CharField(max_length=200)
image2 = models.ImageField(blank=True, upload_to='media/')
img2description = models.TextField()

titleimg3 = models.CharField(max_length=200)
image3 = models.ImageField(blank=True, upload_to='media/')
img3description = models.TextField()

titleimg4 = models.CharField(max_length=200)
image4 = models.ImageField(blank=True, upload_to='media/')
img4description = models.TextField()

titleimg5 = models.CharField(max_length=200)
image5 = models.ImageField(blank=True, upload_to='media/')
img5description = models.TextField()

最佳输出将是 django admin 中的输入字段,其中加号可以添加多个图像 如果有人能引导我朝着正确的方向前进,那将非常有帮助。

【问题讨论】:

    标签: django python-3.x database model


    【解决方案1】:

    将图像制作成内联。首先给他们自己的模型类:

    class Image(models.Model):
        content = models.ForeignKey(contentimage, on_delete=PROTECT). # this is what connect the two models
        title = models.CharField(max_length=200)
        image = models.ImageField(blank=True, upload_to='media/')
        description = models.TextField()
    

    然后在后台注册类:

    class ImageInlineAdmin(admin.InlineModelAdmin):
        extra = 0
        model = Image
    

    然后在你的 contentimage admin 中用一行注册内联:

    inlines = [ImageInlineAdmin]
    

    【讨论】:

      猜你喜欢
      • 2016-05-24
      • 2017-01-10
      • 2019-01-19
      • 2017-11-02
      • 2021-10-10
      • 2021-08-16
      • 2015-06-09
      • 2022-11-01
      • 2014-10-20
      相关资源
      最近更新 更多