Jamie Smith
Jamie Smith

Reputation: 105

Filename only in django form field

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

Upvotes: 0

Views: 1773

Answers (2)

Jamie Smith
Jamie Smith

Reputation: 105

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

Upvotes: 2

Cyrlop
Cyrlop

Reputation: 1984

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

Upvotes: 0

Related Questions