Reputation: 584
According to the Document model below, the 'document.upload.name' in the template will display like "user_NAME/smile.jpg".
I want to split the "user_NAME/smile.jpg" by '/'. So in the template, it will only display "smile.jpg".
I use the 'value.split' in the filter of 'upload_extras'. but the error was: 'str' object has no attribute 'filter_function'.
this is the template:
<td><a href="{{ document.upload.url }}" target="_blank">{{
document.upload.name|filename_extract }}</a></td>
this is my function in upload_extras.py
#upload_extras.py
from Django import template
register =template.Library
@register.filter('filename_extract')
def filename_extract(value):
'''extract the file name from the upload_to_path'''
folder, filename = value.split('/')
return filename
And the last is the model:
# Create your models here.
def upload_to_path(instance, filename):
return 'user_{0}/{1}'.format(instance.user.username, filename)
class Document(models.Model):
uploaded_at = models.DateTimeField(auto_now_add=True)
upload = models.FileField(upload_to=upload_to_path)
user = models.ForeignKey(User, on_delete=models.CASCADE)
Upvotes: 0
Views: 2533
Reputation: 584
from django import template
register = template.Library()
@register.filter('filename')
def filename(value):
folder, filename=value.split("/")
return filename
I changed the function name from 'filename_extract' to 'filename'. it is working now. this is a very wired situation.
Upvotes: 0
Reputation: 1204
You need to load your custom filter in the template.
At the top of your template, add
{% load upload_extras %}
Upvotes: 1