0

I have a model that contains a filefield and am using a modelform to add instances. When I come to modify an instance the form shows the current file and displays the file path ie library/filename.

Is there a way to show just the filename in the form?

Thanks

Jamie Smith
  • 105
  • 2
  • 3
  • 9

2 Answers2

2

I got around this by using javascript.

I added the following to my model..

def filename(self):
    return os.path.basename(self.file.name)

Then added this into my javascript in my template

{% block javascript %}
<script>

{% if part.file %}
$('[href="{{ part.file.url }}"]').html("{{ part.filename }}");
{% endif %}

</script>
{% endblock %}

This changed the link to show just the filename

Jamie Smith
  • 105
  • 2
  • 3
  • 9
0

A FileField will use by default the FileInput widget that produces a <input type="file"> HTML tag. I don't think you can change the default "display full path" behaviour from Django, check this post.

However, you can customise things in your ModelForm like that:

class YourForm(ModelForm):
    class Meta:
        ...
        widgets = {
            'your_file_attribute': FileInput(attrs={'html_attribute': value}),
        }
Cyrlop
  • 1,894
  • 1
  • 17
  • 31