0
votes

I am using django's modelformset_factory form for uploading and editing images. Currently when i display the forms it shows forms with existing data as follows:

  • field name: Currently : link to image (e.g.: images/filename.jpg)
  • Change: image input field
  • check box to delete

How can I change the display of (Currently : link to image (e.g.: images/filename.jpg))? would like to change the image link to display image name instead and open it in a new window when user clicks it. I have checked django's documentation to manually render the form but could not find related information.

Thank you!

Models:

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)
1
Could you post your respective model? - Edwin Lunando

1 Answers

0
votes

The solution is to subclass ClearableFileInput class and override the following:

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,}

Now the output looks as below:

  • Field name: Current Picture
  • Change: Image input field
  • Check box to delete

Django reference documentation