0

I am rendering a simple form with a file field.

class ReviewForm(forms.ModelForm):

    class Meta:
        model = Review

        fields = [
            'file',
        ]

        widgets = {
            'file': forms.ClearableFileInput(),
        }

While rendering, the form shows Current file - /xyz/xyz/xyz.pdf besides the file input.

However, I do not allow direct access to the files. All requests goes through the analytics_logger function before loading the file.

So, I want to customise the Current file html from

Current file - <a href="{0}">{1}</a> to

Current file - <a href="{% url 'analytics_logger' {0} %}">{1}</a>

I also don't want to display the full path of the file. Only the filename should be displayed.

How can I do it in Django 3.x?

Chandragupta Borkotoky
  • 1,596
  • 1
  • 11
  • 16

1 Answers1

1

Following steps are recommended in case of CustomClearableFileInput().

  1. Override the template_name variable of the ClearableFileInput class. A new class can be created in the same forms.py file.

class CustomClearableFileInput(ClearableFileInput):
  template_name = 'widgets/customclearablefileinput.html'
  1. Create a new file widgets/customclearablefileinput.html in the templates directory.

  2. Fill the widgets/customclearablefileinput.html file by modifing the original code of the widget template as per your requirement.

  3. You can change the href tag in the customclearablefileinput.html to wrap the link in the analytics_logger.

    <a href="{% url 'analytics_logger' widget.attrs.analytics_logger_id %}"> {{ widget.value }} </a>

  4. Next you can pass variables as part of form attributes that can accessed to replace the native full filename and customise the url tag.

    <a href="{% url 'analytics_logger' widget.attrs.analytics_logger_id %}"> {{ widget.attrs.filename }} </a>

  5. Following steps are recommended to pass the variables. Pass the variables while initilizing the form in the views.py

    form = ReviewForm(instance= reviewform_instance, analytics_logger_id=reviewform_instance.pk, filename = reviewform_instance.filename)
  6. Next, override the init method of the form and update the attributes of the field.

    self.fields['processed_book'].widget.attrs.update( {'analytics_logger_id': analytics_logger_id, 'filename': filename,})
  7. Include the following in the settings.py

    FORM_RENDERER = 'django.forms.renderers.TemplatesSetting'

  8. Add 'django.forms' to INSTALLED_APPS in settings.py.

  9. Now, you can include the new overridden class in the widget.

    class Meta:
        model = Review
    
        fields = [
            'file',
        ]
    
        widgets = {
            'file': CustomClearableFileInput(),
        }
    
Chandragupta Borkotoky
  • 1,596
  • 1
  • 11
  • 16