我正在使用django的modelformset_factory表单来上传和编辑图像。目前,当我显示表单时,它显示具有现有数据的表单,如下所示:
如何更改(当前:链接到图像(例如:images / filename.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)
答案 0 :(得分: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,}
现在输出如下所示: