Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Modifying a Django Rest Framework Request
I have a Django rest framework api set up, and I'm trying to insert the current time into incoming PUT requests. I currently have: class ItemViewSet(viewsets.ModelViewSet): queryset = Item.objects.filter(done = False).order_by('-time') serializer_class = ItemSerializer paginate_by = None def list(self, request, *args, **kwargs): self.object_list = self.filter_queryset(self.get_queryset()) serializer = self.get_serializer(self.object_list, many=True) return Response({'results': serializer.data}) This handles partial updates, but I would like to be able to send a request setting an Item to done = True and have the api also insert a unix timestamp into the data sent to the serializer. Could I alter the request object like this, or is there a better way? def put(self, request, *args, **kwargs): request.data['time'] = time.time() return self.partial_update(request, *args, **kwargs) -
Why does my django cache return nothing? Not even 'None'
I have the following three functions. The bottom function calls on the top two functions. I will get an error when multiplying the variables c=m*b 'unsupported operand type(s) for *: 'NoneType' and 'float'' and as you can see m returns nothing. So my two problems are that btc_to_hourl3 does not show 'None' or a value (and therefore skips the if statement). And secondly when printing totalUserL3hours(user1) in last function it prints nothing even though the function called shows a cached variable? def btcToHourL3(): btc_to_hourl3 = cache.get('btc_to_hourl3') print("btc to hourl3 cached is : ".format(btc_to_hourl3)) #shows as nothing when is something? if btc_to_hourl3 is None: main_api = 'https://api.nicehash.com/api?method=balance&id=keyhere' json_data = requests.get(main_api).json() balance1 = json_data['result']['balance_confirmed'] print("Nice hash L3 balance is: {}".format(balance1)) btc_to_hourl3 = float(balance1)/totalMachineHoursWorkedMonthL3() m = float(btc_to_hourl3) print("Total btc to every hour is: {}".format(btc_to_hourl3)) cache.set('btc_to_hourl3', m, 900) #cache for 15 mins return float(btc_to_hourl3) def totalUserL3hours(user1): user_L3_hrs = cache.get('user_L3_hrs'+user1.username) print("User l3 cache hours are {}".format(user_L3_hrs)) ####Prints 'None' when it is none ie after 1800secs. Prints 511 when works if user_L3_hrs is None: a=0.0 l3_total = user1.L3s.all() for l3 in l3_total: x = l3.indivMachineHoursWorked() a=a+x cache.set('user_L3_hrs'+user1.username, float(a), 1800) print("User l3 hours are {}".format(a)) return user_L3_hrs def TotUserL3Mined(user1): # a = 0.0 # l3_total = request.user.L3s.all() … -
How can I add the `order_status_count` to as the same level as the `results` list?
I want to add the order_status_count to as the same level as the results list: I tried bellow code: serializer: class OrderFilterSerializer(ModelSerializer): order_type = serializers.CharField(write_only=True, allow_null=True) order_user_name = serializers.SerializerMethodField() order_status_count = serializers.SerializerMethodField(read_only=True) def get_order_status_count(self, order): ..... return order_status_count view: class OrderSerializerListAPIView(ListAPIView): serializer_class = OrderFilterSerializer # pagination_class = OrderPageNumberPagination ..... But the bellow is like this: HTTP 200 OK Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept { "count": 140, "next": "http://localhost:8000/api/abc/order/list/?page=2", "previous": null, "results": [ { "id": 1, "order_user_name": "test01", "order_status_count": { "paid_finished_count": 5, "paid_unfinish_count": 68, "unpay_count": 49 }, "order_num": "15108988238922", ..... }, ...... You see the order_status_count in every item now: "order_status_count": { "paid_finished_count": 5, "paid_unfinish_count": 68, "unpay_count": 49 }, This is not fit my envision. How can I add the order_status_count to as the same level as the results list? -
Does migrations directory in django project should be pushed to git repo?
In django project, when models changed the migrations file will be changed, if add migrations directory to git will raise conflict to others, if not add sometimes will raise server error when migrated. How do you solve this? -
Calling api from django view error. forbidden (csrf token is missing or incorrect)
I seen alot of other solution, tried it but problem still persist. When i do a requests.get, it works fine but when i'm doing requests.post. I got this forbidden (csrf token is missing or incorrect) error. Here is my code models.py class TestPost(models.Model): # reminderId = models.AutoField() book = models.CharField(max_length=10, blank=True, null=True) author = models.CharField(max_length=10, blank=True, null=True) date = models.DateTimeField(blank=True, null=True) serializer.py class TestPostSerializer(serializers.ModelSerializer): # valid_time_formats = ['%H:%M', '%I:%M%p', '%I:%M %p'] # time = serializers.TimeField(format='%I:%M %p', input_formats=valid_time_formats, allow_null=True) date = serializers.DateTimeField(format="%Y-%m-%d %I:%M %p") class Meta: model = TestPost fields = ('id', 'book', 'author', 'date') views.py from django.http import HttpResponse import requests def my_django_view(request): if request.method == 'POST': r = requests.post('http://127.0.0.1:8000/api/test/', params=request.POST) else: r = requests.get('http://127.0.0.1:8000/api/test/', params=request.GET) if r.status_code == 200: return HttpResponse('Yay, it worked') return HttpResponse('Could not save data') class TestPostViewSet(viewsets.ModelViewSet): permission_classes = [AllowAny] queryset = TestPost.objects.all() serializer_class = TestPostSerializer I did a POST method on the url of the function but error Forbidden (CSRF token missing or incorrect.): /test/ [22/Jan/2018 16:59:09] "POST /test/ HTTP/1.1" 403 2502 -
"http method not bound to view" when documenting class-based view in drf_yasg
Previously, I documented my function-based views like this: @swagger_auto_schema( operation_id='ChangePassword', methods=['POST'], request_body=ChangePasswordSerializer, responses={ '200': 'empty response body', }) def change_password(request): # code here We then switched our views to class-based, so I simply copy-pasted the documentation decorator over to the post method: class UserChangePasswordView(APIView): @swagger_auto_schema( operation_id='ChangePassword', methods=['POST'], request_body=ChangePasswordSerializer, responses={ '200': 'empty response body', }) def post(self, request): # code here However, on running this decorator, drf_yasg threw the exception File "/usr/local/lib/python3.6/site-packages/drf_yasg/utils.py", line 126, in decorator assert all(mth in available_methods for mth in _methods), "http method not bound to view" What is going on? What does this error message mean? -
Django generic date based views How to get the date lookup?
There is a function in a generic class based view called _make_single_date_lookup(self, date) def _make_single_date_lookup(self, date): """ Get the lookup kwargs for filtering on a single date. If the date field is a DateTimeField, we can't just filter on date_field=date because that doesn't take the time into account. """ date_field = self.get_date_field() if self.uses_datetime_field: since = self._make_date_lookup_arg(date) until = self._make_date_lookup_arg(date + datetime.timedelta(days=1)) return { '%s__gte' % date_field: since, '%s__lt' % date_field: until, } else: # Skip self._make_date_lookup_arg, it's a no-op in this branch. return {date_field: date} I am interested in the lookup part: return { '%s__gte' % date_field: since, '%s__lt' % date_field: until, } How do you get access to the lookup for the month in a MonthArchiveView? -
Setting up Django on a clean VM: issue linking runserver to VM's ip
I'm setting up my Django site on a clean Ubuntu VM. Gone through the process of installing the necessary tools, I follow this tutorial and apart from the additional python packages I've added for my site it's the same process. According to this instructional guide to check whether everything is running smoothly you run python manage.py runserver 0.0.0.0:8000 and it should then run on the IP:8000 of the site. above is the instance of this running and this above shows the external ip of the google cloud instance running this. However when i try to visit http://35.227.49.155:8000/ I get This site can't be reached and it's double confirmed with no activity on the shell on a request picked up. -
How to create dynamic webscraper in Django using BeautifulSoup
I am trying to a dynamic webscraper using Django. I have a html button in which it has buttons so it is like when i will press the button it will start webscraper and will save the data into database and later on from another button i can download that data into CSV format. Now I have prepared the html page for buttons. I have written webscraper script and in my views.py i have imported that scraper file and called that function but when i type python manage.py runserver scrapers starts but my web page is not reachable. First how can i solve this problem. Second how can i connect my scraper with the html button Third how i can save the data into database Fourth how can i download them into csv when i press the button Below is my Views.py from django.shortcuts import render from django.conf.urls import url from django.conf.urls import include from django.http import HttpResponse from bs4 import BeautifulSoup import requests import Up# this is the web scraping file # Create your views here. #def index(request): # first = {"here":"will enter more details"} # return render(request, "files/first-page.html", context=first) #return HttpResponse("<em>Rera details will be patched here</em>") #uncomment this … -
Django, inline and nested, formsets in a single form
A part the broader problem of a great and mature framework not fully complete at some of its edges ( but this is mostly a rant...), my current issue is not with inline formsets but with inline nested formsets. For example: 1) a warehouse registration heading, with: number, date, type, etc. 2) several related articles (1 to many), with: code, upload/download flag; 3) several line items related to the article (1 to many): quantity, volume of container, identification of container, etc. So two levels of relationships to be maintained through a single form, that is: created and updated. Should I keep trying with something like: https://www.yergler.net/2013/09/03/nested-formsets-redux/, which the author itself warns to be careful at, or should I think of implementing just this form in Vue, let’s say, and use Django only as a backend engine? -
Replicate databases within AWS RDS
I have two database (db1) and (db2) created in one Postgres RDS, Is it possible to configure one as master and another as a slave to replicate data. -
Fields not sent in POST for ModelForms are overwritten as blank values
Just realised that we have been silently losing data on our web platform because some of the fields in the ModelForm are hidden in some contexts and not being sent in the POST request. As a result, these fields were being overwritten as blank values and erasing the previous value. (Thank God, we use django-reversion to track changes, though we need to spend some time to recover the data). I saw this old post on django-developers group that discusses exactly this issue. Has anyone been able to figure out a good work around for this yet (apart from not using Model Forms) so that fields that are not sent in the POST request in ModelForms remain untouched? (Note that we do need these fields in the Meta class in the ModelForm since they are used in some contexts but not all) -
Django in shared hosting/cpanel
hey guys i have the issue with my django app so what should i do?i have shared hosting account on which i am trying to upload my django app, please help this is the code of .htaccess file DO NOT REMOVE. CLOUDLINUX PASSENGER CONFIGURATION BEGIN PassengerAppRoot "/home/dasawork/store" PassengerBaseURI "/test" PassengerPython "/home/dasawork/virtualenv/store/3.5/bin/python3.5" # DO NOT REMOVE. CLOUDLINUX PASSENGER CONFIGURATION END it worked at night first and then in the morning it wasn't working and giving the error "/home/dasawork/public_html/test/.htaccess: Invalid command 'PassengerAppRoot', perhaps misspelled or defined by a module not included in the server configuration". hosting providers changed my root dir name! like when it worked it was "'/newhome/dasawork/...." but on the morning it was changed to "/home/dasawork/..." so can this cause the problem ? please help -
How to make loop variables accessible from block-endblock
I am trying to write code for the index page of a blogging site. The index page will fetch blog title, date, author details and blog content and put it on the index page. I am having an issue making jinja2 templates work for this. Here is my base.html templates, which will be used site wide. <head> <meta charset="UTF-8"> <link type="text/css" rel="stylesheet" href="{{ static ('css/style.css') }}"/> <title>{% block title_block %}{% endblock %}</title> </head> <body> <div class="jumbotron"> <div class="container-fluid"> <div class="row"> <div class="col-2"> </div> <div class="col-10"> <h3 class="hdr hrborder">{% block posttitle scoped %}{% endblock %}</h3> </div> </div> <div class="row"> <div class="col-2 vrborder text-right"> Published: {% block postdate %}{% endblock %} Author: {% block postauthor %} {% endblock %} </div> <div class="col-10"> {% block postcontent %}{% endblock %} </div> </div> </div> </body> And here is the child template {% extends 'core/base.html' %} {% block title_block %} Blogs {% endblock %} {% for post in posts %} {% block posttitle scoped %}{{ post.post_title }}{% endblock %} {% block postdate scoped %}{{ post.post_date }}{% endblock %} {% block postauthor scoped %}{{ post.post_author }}{% endblock %} {% block postcontent scoped %}{{ post.post_content }}{% endblock %} {% endfor %} But this is not workin. I am … -
Django. Error in "create_superuser()"
I got error when i trying to create "super user" by "manage.py createsuperuser". Traceback: File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/mnt/e/Work/WEB/django/72tob/env/lib/python3.5/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/mnt/e/Work/WEB/django/72tob/env/lib/python3.5/site-packages/django/core/management/__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/mnt/e/Work/WEB/django/72tob/env/lib/python3.5/site-packages/django/core/management/base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "/mnt/e/Work/WEB/django/72tob/env/lib/python3.5/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 59, in execute return super().execute(*args, **options) File "/mnt/e/Work/WEB/django/72tob/env/lib/python3.5/site-packages/django/core/management/base.py", line 335, in execute output = self.handle(*args, **options) File "/mnt/e/Work/WEB/django/72tob/env/lib/python3.5/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 179, in handle self.UserModel._default_manager.db_manager(database).create_superuser(**user_data) TypeError: create_superuser() got an unexpected keyword argument [model.py] from time import timezone from django.db import models from django.contrib import admin from django.contrib.auth.models import User from django.contrib.auth.models import BaseUserManager from django.contrib.auth.models import AbstractBaseUser from django.contrib.auth.models import PermissionsMixin class TemporaryBanIp(models.Model): class Meta: db_table = "TemporaryBanIp" ip_address = models.GenericIPAddressField("IP адрес") attempts = models.IntegerField("Неудачных попыток", default=0) time_unblock = models.DateTimeField("Время разблокировки", blank=True) status = models.BooleanField("Статус блокировки", default=False) def __str__(self): return self.ip_address class TemporaryBanIpAdmin(admin.ModelAdmin): list_display = ('ip_address', 'status', 'attempts', 'time_unblock') search_fields = ('ip_address',) class AuthUserManager(BaseUserManager): def create_user(self, email, username, first_name, last_name, patronymic, birth_day, inn_id, passport_s, passport_n, password=None): if not email: raise ValueError('Users must have an email address') user = self.model( email=AuthUserManager.normalize_email(email), username=username, last_name=last_name, first_name=first_name, patronymic=patronymic, birth_day=birth_day, inn_id=inn_id, passport_s=passport_s, passport_n=passport_n, ) user.is_admin = True user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, first_name, last_name, patronymic, birth_day, inn_id, passport_s, passport_n, … -
Run program on server forever without manually starting it
I have created an application which resides on a server. The application uses Django to connect. So, if I want to access the web page I have to run the following command to start the server - python manage.py runserver ip adress:port number What is the way to keep it running all the time even after shutting down my computer? -
django no module name 'config'
I wrote these apps using python2 and now am using python 3. I've tried: 1) Changing to a new virtualenv and reinstalling requirements 2) pip install config -> returns a new Syntax error in an Exception... 3) pip install django-config 4) I keep getting the following error: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 308, in execute settings.INSTALLED_APPS File "/usr/local/lib/python3.6/site-packages/django/conf/__init__.py", line 56, in __getattr__ self._setup(name) File "/usr/local/lib/python3.6/site-packages/django/conf/__init__.py", line 41, in _setup self._wrapped = Settings(settings_module) File "/usr/local/lib/python3.6/site-packages/django/conf/__init__.py", line 110, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/local/Cellar/python3/3.6.3/Frameworks/Python.framework/Versions/3.6/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 941, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 941, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked ModuleNotFoundError: No module named 'config' I'm really stuck because i can't run these project that … -
How to synchronise algolia with database only when deleteing, adding and updating model instance
According to algoliasearch-django document: 'AUTO_INDEXING: automatically synchronize the models with Algolia (default to True).' For my understand, if I set AUTO_INDEXING to True, whatever I update a model instance or update model (e.g. add a new field), it will synchronise Algolia with my own database (or model). However, what I want to do is synchronise Alogolia on demand, for example, only synchronise them when a model instance is change, added or deleted. Are there any way to implement this? Thanks. -
Make detail page for each A/B test experiment result
I have been making A/B testing system using Django and dashboard using django controlcenter. Now I have a dashboard page including results of all active experiments. What I want to do is spliting a dashboard page for each experiment. I have tried a way using urlpatterns = [url(r'^admin/dashboard/mydash/(?P<exp_id>[0-9])/$', views.exp_dashboard), ] in urls.py and def exp_dashboard(request, exp_id): exp = get_object_or_404(Experiment, pk=exp_id) exp = Experiment.objects.get(pk=exp_id) return HttpResponse('experiment %s'%exp_id) in views.py But I do not know how to return dashboard page from exp_dashboard, not returning HttpResponse as usual. Do you have any advice to do this? -
Django 2.0 UpdateView NoReverseMatch
Trying to use UpdateView to update a model object with name "Tag" Here is the model: NAME_REGEX = r'^[a-zA-Z0-9\s.\-]+$' class Tag(TimeStampModel): name = models.CharField(max_length=40, validators = [ RegexValidator(regex=NAME_REGEX, message='name must be alphanumeric, may contain - _', code='invalid tag name')], unique=True) slug = models.SlugField(max_length=60, unique=True, blank=True) text = models.TextField(blank=True) def __str__(self): return self.name def get_absolute_url(self): url = reverse('tags:tag_detail', kwargs={'slug':self.slug}) print('Tag *************** 010 ********************') print(url) return url def save(self, *args, **kwargs): self.slug = make_slug(self.name) super().save() I am able to create a Tag using CreateView, list the Tags using ListView and access the Tag detail using DetailView. I am also able to edit the tag using a function based view. However, it falls down with UpdateView. Here are the urls: urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path('tag_list/', views.TagListView.as_view(), name='tag_list'), path('tag_detail/<slug:slug>/', views.TagDetailView.as_view(), name='tag_detail'), path('create_tag/', views.CreateTagView.as_view(), name = 'create_tag'), path('update_tag/<slug:slug>/', views.UpdateTagView.as_view(), name = 'update_tag'), path('category_list/', views.CategoryListView.as_view(), name = 'category_list'), path('category_detail/<slug>/', views.CategoryDetailView.as_view(), name = 'category_detail'), ] In a template called "tag_detail.html" I provide a link that should take the user to an edit form as follows: <p class="slm-red"> {{ tag_dict.slug }} <br> <a href="{% url 'tags:update_tag' tag_dict.slug %}">Edit Tag</a> </p> (I've printed the value of the slug before the link. That is not the problem. The … -
Can not assign must be a instance. Django
Error : Cannot assign "'1'": "OrderInfo.ordertype" must be a "Orders" instance. I know that it means 'string' must to be an 'instance' (maybe model object) But, I have no idea why string is not allowed. This is my code. Models.py : class OrderInfo(models.Model): post = models.OneToOneField(Post) ordertype = models.ForeignKey(Orders) company = models.CharField(max_length=50, blank=True, null=True) position = models.CharField(max_length=50, blank=True, null=True) class Post(models.Model): board = models.ForeignKey(Board) writer = models.CharField(max_length=50, blank=True, null=True) writtendate = models.DateTimeField(blank=True, null=True) editeddate = models.DateTimeField(blank=True, null=True) subject = models.CharField(max_length=50, blank=True, null=True) text = RichTextField() hits = models.IntegerField(default=0) class Orders(models.Model): order = models.CharField(max_length=50, blank=True, null=True) Forms.py : class OrderEditForm(forms.ModelForm): qs = Orders.objects.all() list = [(order.id, order.order) for order in qs] ##### list's value is [('1', 'A'), ('2', 'B')] ordertype = forms.CharField(widget=forms.RadioSelect(choices=list)) class Meta: model = OrderInfo fields = ('ordertype', 'company', 'position') class PostForm(forms.ModelForm): class Meta: model = Post fields = ('subject', 'text') def __init__(self, *args, **kwargs): super(PostForm, self).__init__(*args, **kwargs) self.fields['subject'].required = True views.py def order_post_edit(request, board_id, post_id): post = get_object_or_404(Post, id=post_id) if request.method == "POST": form = PostForm(request.POST, instance=post) orderform = OrderEditForm(request.POST, instance=post.orderinfo) if form.is_valid(): print(request.POST['ordertype']) print(orderform.fields) post = form.save(commit=False) post.editeddate = timezone.now() post.save() orderform.save() return redirect('order_post', board_id=board_id, post_id=post.id) else: form = PostForm(instance=post) orderform = OrderEditForm(instance=post.orderinfo) return render(request, 'board/order/order_post_edit.html', {'form': … -
Accessing relative import beyond top-level package
i have searched across stackoverflow and i havent been able to come up with an answer. I have this directory: project/ util/ utility.py models.py So here is a description of what each file does models.py : contains a list of my django models utility.py: from ..models import * [...] May i know why i keep getting this error: ValueError: attempted relative import beyond top-level package? And how can i solve this? -
Protect third party iframe like from being used elsewhere
I am using a third party (Company X) service for a part of my app (Django based), which is behind a secure login. The content from X is delivered in an iframe that is simply embedded in one of my pages. I have spent a lot of time building the custom content in X's app (it is a custom, interactive geology tool) and my subscription with X is pricey as well. I want to protect against the possibility of one of my users sharing the iframe link with other coworkers or even users in other companies and simply using my content from X without even having to log into my app. Unfortunately, X has no way to limit the iframe content by IP or any other type of link security. I know, sounds crazy but that's the way it is right now. What would be the best way to build my own security solution? Is there a way to use another server as an intermediary, so that when the client opens the page my live server hits my intermediary server that fetches the content from X? Then I only accept requests on my intermediary server from my live server. Thanks … -
nginx config for flower celery as a subdomain
I am trying to setup nginx config to run my flower instance in a subdomain. here is the config: upstream myapp { server unix:///var/www/myapp/application/live.sock; } server { listen 80; server_name app.myapp.com; charset utf-8; client_max_body_size 75M; # Django media location /media { alias /var/www/myapp/application/app/media; expires 60d; add_header Cache-Control public; } location /static { alias /var/www/myapp/application/app/static; } location / { uwsgi_pass myapp; include /etc/nginx/uwsgi_params; } } server { listen 80; server_name flower.myapp.com; charset utf-8; error_log /var/log/nginx/error.log debug; location / { proxy_pass http://localhost:5555; proxy_set_header Host $host; proxy_redirect off; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; } } The config for app.myapp.com is working. But if I go to flower.myapp.com it is giving me 504 Gateway Time-out after loading for some seconds. what am I doing wrong? -
Django filter tag not working: AttributeError at / 'str' object has no attribute 'filter_function
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)