在 ModelChoiceField 中渲染图像列表

Render the images list inside a ModelChoiceField

我使用 Bootstrap4 开发了一个表单,用于创建博客 post。此表单链接到一个模型,其中有两个 ForeignKey:一个 FileField 和一个 ImageField。

如果我使用默认的表单渲染方法({{ form.as_p }})我可以创建一个博客post但是FileField 和ImageField 都是用单一上传类型的名称渲染的。我想看的不是单个图像的名称,而是图像。然后我尝试使用这个:

<div class="form-group mb-4">
    <select class="form-control">
        {% for img in geoform.image %}
            <option value="{{ img.pk }}"> <img class="img-fluid" src="{{ img.path }}" alt="{{ img.name }}"> </option>
        {% endfor %}
    </select>
</div>

但我看到一个空列表。在页面源代码中我看到了这个:

<select class="form-control">
        <option value=""> <img class="img-fluid" src="" alt=""> </option>
        <option value=""> <img class="img-fluid" src="" alt=""> </option>
        <option value=""> <img class="img-fluid" src="" alt=""> </option>
        <option value=""> <img class="img-fluid" src="" alt=""> </option>
</select>

我在图像模型中有四个对象。由于我不明白对象没有正确呈现的原因。

这是型号:

class GeoBlogFile(models.Model):
    name = models.CharField(max_length=70)  
    path = models.FileField(upload_to='geoblog/documents/%Y/%m/%d')

    def __str__(self):
        return self.name

class GeoBlogImage(models.Model):
    name = models.CharField(max_length=70)  
    path = models.ImageField(upload_to='geoblog/images/%Y/%m/%d')

    def __str__(self):
        return self.name

class GeoBlog(models.Model):
    title = models.CharField(max_length=70, unique=True)
    slug_title = models.SlugField(max_length=70, unique=True)
    contents = models.TextField(max_length=200)
    file = models.ForeignKey(GeoBlogFile, on_delete=models.CASCADE, related_name="related_file", blank=True, null=True)
    image = models.ForeignKey(GeoBlogImage, on_delete=models.CASCADE, related_name="related_image", blank=True, null=True)
    publishing_date = models.DateTimeField(default=timezone.now, blank=True)
    geom = models.PointField(srid=3857)

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse("single_geopost", kwargs={"slug_title":self.slug_title})

这是表格:

class GeoBlogPostForm(forms.ModelForm):
    title = forms.CharField(
        max_length=70,
        widget=forms.TextInput(
            attrs={
                "placeholder": "Titolo",
                "type": "text",
                "id": "id_name",
                "class": "form-control form-control-lg",
                }
            ),
        )
    contents = forms.CharField(
        max_length=200,
        widget=forms.Textarea(
                attrs={
                    "placeholder": "Contenuti",
                    "type": "text",
                    "id": "id_contents",
                    "class": "form-control",
                    "rows": "2",
                    }
            ),
        )
    file = forms.ModelChoiceField(
        widget= forms.Select(
            attrs={
                "id": "id_file",
                "class": "custom-select",
                }
            ),
        empty_label="Select the file",
        queryset= GeoBlogFile.objects.all(),
        )
    image = forms.ModelChoiceField(
        widget= forms.Select(
            attrs={
                "id": "id_image",
                "class": "custom-select",
                }
            ),
        empty_label="Select the image",
        queryset= GeoBlogImage.objects.all(),
        )
    geom = forms.PointField(
        widget=forms.OSMWidget(
            attrs={
                'default_lat': 0,
                'default_lon': 0,
                'default_zoom': 2,
                }
            ),
        )
    publishing_date = forms.DateTimeField(
        widget=forms.DateTimeInput(
            attrs={
                "placeholder": "dd/mm/yyyy HH:MM:SS",
                "type": "text",
                "formats": "%m/%d/%Y %H:%M:%S",
                "id": "publishing_date_field",
                'class': 'form-control',
                'data-target': '#publishing_date_field',
                }
            ),
        )

    class Meta:
        model = GeoBlog
        fields = ['title', 'contents', 'file', 'image', 'publishing_date', 'geom']

之前的表格组是许多人的最后一次尝试。是否可以呈现图像列表而不是图像名称列表?

您正在遍历 geoform.image,但那是 geoformBoundField。你有点倒霉,因为它是一个ChoiceField,遍历它给你子控件列表,但它与实际图像无关。

要获取图像,您必须求助于实际 Field:

{% for img in geoform.fields.image.queryset %}

此外,请确保您在 <img> 标签中使用的 url 是上传文件的正确前缀媒体 url:

src="{% get_media_prefix %}{{ img.path.url }}"