0

我正在使用 django 的 modelformset_factory 表单来上传和编辑图像。目前,当我显示表单时,它会显示包含现有数据的表单,如下所示:

  • 字段名称:当前:图片链接(例如:images/filename.jpg)
  • 更改:图像输入字段
  • 要删除的复选框

如何更改(当前:链接到图像(例如:图像/文件名.jpg))的显示?想将图像链接更改为显示图像名称,并在用户单击它时在新窗口中打开它。我检查了 django 的文档以手动呈现表单,但找不到相关信息。

谢谢!

楷模:

class BaseImageAbstractModel(models.Model):
    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey('content_type','object_id')

    class Meta:
        abstract = True

class ImageAbstractModel(BaseImageAbstractModel):
        user = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE)
        name = models.CharField(max_length=50, blank=True)
        description = models.TextField(max_length=3000)
        picture = models.ImageField(upload_to='images')
        submit_date = models.DateTimeField(default=None)
        is_public = models.BooleanField(default=True)
        is_removed = models.BooleanField(default=False)

        class Meta:
            abstract = True

        def __str__(self):
            pass

class Image(ImageAbstractModel):    
    class Meta:
        verbose_name = "Image"
        verbose_name_plural = "Images"

        def __str__(self):
            return self.name
class ImageForm(BootstrapForm, ModelForm):

    class Meta:
        model = Image
        fields = ('picture', 'name')

ImgFormSet = modelformset_factory(Image, form=ImageForm, extra=5, can_delete=True)
4

1 回答 1

0

解决方案是继承 ClearableFileInput 类并覆盖以下内容:

class image_widget(ClearableFileInput):
     initial_text = ugettext_lazy('')
     template_with_initial = ('%(initial_text)s <a target="_blank" href="%(initial_url)s">%(initial)s</a> '
    '%(clear_template)s<br />%(input_text)s: %(input)s')

    def get_template_substitution_values(self, value):
       return {
           'initial': 'Current Picture',
           'initial_url': conditional_escape(value.url),
    }

class ImageForm(BootstrapForm, ModelForm):

    class Meta:
        model = Image
        fields = ('picture', 'name')
        widgets = {'picture': image_widget,}

现在输出如下所示:

  • 字段名称:当前图片
  • 更改:图像输入字段
  • 要删除的复选框

Django 参考文档

于 2017-01-23T08:18:15.623 回答