Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: "AppRegistryNotReady: Apps aren't loaded yet" when deploying to Heroku
I'm consistently running into an error when deploying to production(Heroku), but the app works fine on my localhost. I see that many other people have this issue but none of the solutions work for me. One important note is that I do not call django.setup(), because when I do I get another error (auth.User model not found), but according to the Django docs you should not have to call that when running the app on a web server (as I am). I've been really stuck on this so would appreciate any help anyone can give. The error is: File "/app/.heroku/python/lib/python3.6/site-packages/django/apps/registry.py", line 136, in check_apps_ready 2021-03-26T10:33:44.756357+00:00 app[web.1]: raise AppRegistryNotReady("Apps aren't loaded yet.") 2021-03-26T10:33:44.756413+00:00 app[web.1]: django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. I'm on Django 3.1.7, and looked at my requirements.txt and i believe my apps are up to date. Below is my code: Procfile release: python manage.py migrate web: daphne django_project.asgi:application --port $PORT --bind 0.0.0.0 -v2 worker: python manage.py runworker channels --settings=django_project.settings -v2 blog/models.py print('~~~\n\nvery top in blog/models.py\n\n~~~') from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse from datetime import datetime, timedelta # we're inheriting from the models.Model class Post(models.Model): title = models.CharField(max_length=100) # character field … -
Cleaning up file based variables 00:01 ERROR: Job failed: exit code 1
When I am trying to commit changes to gitlab for continuous integrations i am facing this error Cleaning up file based variables 00:01 ERROR: Job failed: exit code 1 I am running 2 stages building and testing at the moment here is my script for testing - pytest -p no:warnings --cov=. - flake8 . - black --check --exclude=migrations . - isort . --check-only He is trowing this error when he went trough black and is supposed to start isort. And what is interesting is when i am trying to run isort in the terminal his response is UserWarning: Likely recursive symlink detected to /usr/src/app/env/lib warn(f"Likely recursive symlink detected to {resolved_path}") Skipped 1 files I am stuck with this for a while, so any help will be appreciated. tanks in advance -
Django Unittest how to adjust client.post to set data in request.META
I am trying to test a view by posting data to the view, but the view uses a key/value from request.META. How do I adjust my client.post to ensure the request.META data is populated ? The following example isn't working! Example from unittest: with mock.patch("......") as gt: header = {'SOME_SIGNATURE': 'BLAH'} gt.side_effect = ValueError response = self.client.post('/webhook/', data={'input': 'hi'}, content_type='application/json', follow=False, secure=False, extra=header) self.assertEqual(response.status_code, 400) Code from the view: def my_webhook_view(request): # Extract Data from Webhook payload = request.body # THIS LINE CAUSES MY UNITTESTS TO FAIL sig_header = request.META['HTTP_SOME_SIGNATURE'] ...... -
How to update select option from Jquery Ajax successful data
When I click the button I am getting console ouptpur correctly ; but my options are not getting updated. Please help as I new to Ajax,Jquery and Django. I spent more than a week to fix the issues. But no result. Your correction is very much require. Thanks My model is: class Post(models.Model): post_heading = models.CharField(max_length=200) post_text = models.TextField() def __str__(self): return self.post_heading my view is: def getmydata(request): # get the provinces for given country from the # database excluding null and blank values if request.method == "GET" : data = list(Post.objects.all().values()) return JsonResponse({"data": data}) my html template is: <div > <select name="car_maker" id="car_maker"> <option value="volvo">Volvo</option> <option value="saab">Saab</option> <option value="fiat">Fiat</option> <option value="audi">Audi</option> </select> </div> <div class="postacct"> <p>>{{ acct.post_heading }}</p>> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script> <script type="text/javascript"> $('.clickme').click(function(){ let catid; {#catid = $(this).attr("data-catid");#} catid='nil' $.ajax( { type: "GET", url: "/getmydata", data: { post_id: catid, 'csrfmiddlewaretoken': '{{csrf_token}}' }, success: function (data) { console.log(data); $("#car_maker option").remove(); $.each(data.rows, function (index, item) { //jQuery way of iterating through a collection $("#car_maker option").append($('<option>') .text(item.label) .attr('value', item.value)); }) } })}) </script> </body> </html> from ajax i getting the console output: (index):54 {data: Array(2)} data: Array(2)s 0: {id: 1, post_heading: "2", post_text: "two"} 1: {id: 2, post_heading: "1", post_text: "one"} … -
Does Django Rest Framework execute query for SerializerMethodField
I have following Django Rest Framework Serializer: from rest_framework.serializers import SerializerMethodField from posts.api.serializers import CommentSerializer class PostSerializer(ModelSerializer): comments = SerializerMethodField() class Meta: model = Post fields = ('id', 'title', 'comments') def get_comments(self, obj): return CommentSerializer(obj.comments.all(), many=True).data And I have following View: from rest_framework.views import APIView from rest_framework.responses import Response from posts.models import Post class PostsAPIView(APIView): def get(request): posts = Post.objects.all() serializer = PostSerializer(posts, many=True) return Response(serializer.data, status=200) So, My question is, when my serializer is working to prepare JSON of posts, for getting comments of each post, it executes a database query or not? For example, if I have 10 posts, is 11 database queries executed in this view? (1 query to get posts and 10 queries to get comments of each post in serializer). -
Discord - Send messages from a channel to my website in real time
I currently have a python/django platform and a discord community. On my discord server there is a channel "announcements". I would just like that when a message is published in this channel, it goes up to my website in real time. This is in order to convert it into a notification. Currently I managed to upload the messages from the channel to my site in a simple way but not in real time: def discord_get_last_message_id(): message_id = 0 try: message_id = Notification.objects.latest('id').discord_message_id except: pass return message_id def get_channel_messages(): #load last id discord message in DB last_message_id = discord_get_last_message_id() #Base route route = "/channels/"+ DISCORD_CHANNEL_ANNONCES_ID +"/messages" #if first time to DB, load just one item if last_message_id == 0: add = "?limit=1" else: add = "?after="+last_message_id route = route + add data,error_message = request_discord('GET',route) print(data) def request_discord(method,url_access,body={}): data ='' #Call token error_message = '' access_token = discord_get_token() #Call request headers = {'Authorization': access_token} body = body if method=="GET": result = requests.get(DISCORD_BASE_URI + url_access, headers=headers) else: result = requests.post(DISCORD_BASE_URI + url_access, headers=headers,data=body) #Check result if result.status_code != 200 and result.status_code != 201: error_message = "Impossible de d'obtenir un resultat erreur: " + str(result.status_code) else: data = result.json() return data,error_message def discord_get_token(): return … -
Python, Django: Editing inlineformset_factory
inside my app I'm using an inlineformset_factory and right know it's working fine! But when displaying it inside my template the Labels are always staying right above the input-field. Is there any way to display them side-by-side or even move the label as some sort of placeholder inside the input-field? views.py formset = inlineformset_factory(Model_A, Model_B, can_delete=False, extra=0, fields=('fields_01', 'fields_02', 'fields_03')) template.html <form method="post"> {% csrf_token %} {{ formset.management_form }} {% for form in formset %} {{ form }} {% endfor %} <button type="submit">Save</button> </form> Thanks for all your help and have a great weekende! -
Django API throws CORS error when visitor behind proxy
I have a web service built in React that uses a back-end API in Django. I am currently struggling because we have an enterprise customer that is trying to signup but he is getting a CORS error. The surprising thing is that we don't even have CORS enabled on the Django API (ALLOWED_HOSTS is not set) so I don't know why the API is returning this error. The only thing I know is that they're behind a proxy. I am trying to replicate this behavior but when I put myself behind a proxy it still works perfectly... Any idea on what is causing the issue? -
Trying to create a function in Django
Can someone help me please ?! The function should filter some Products with their brands if arguments given if not it should return all products . def return_products(*products): pass -
Is there a way not to remove data from test database between each test
I use the "python manage.py test" for running my tests. I have several tests in my repo and have data dependency between the tests. I have the below structure. Class ABC(APITestCase): def setUp() def tearDown() def test_a() def test_b() Is there any way to not delete the data between each test.(Data should present in test DB when moving from test_a and test b) -
'poll_extras' is not a registered tag library. But I already registered one
This is my customize poll_extras.py file from django import template register = template.Library() def titless(value): """convert a string to upper case""" return value.title() register.filter('titless', titless) I have created this file in (templatetags>> this dir contain init.py file and poll_extras.py file also this dir is inside my poll app ) then I used this tags in one html file (named >> poll.html) here is poll.html few line {% extends 'base.html' %} {% load poll_extras %} {% block content %} <h2>{{"vote vage" | titless}}</h2> <h3>{{question.title}}</h3> ..... Now i am getting this error 'poll_extras' is not a registered tag library. but i did register here is tree if helpful +---ems | +---static | | \---css | | styles.css | | | \---templates | | base.html | | | +---auth | | login.html | | success.html | | | +---employee | | add.html | | delete.html | | detail.html | | edit.html | | home.html | | | \---polls | detail.html | index.html | poll.html | \---polls | admin.py | apps.py | context_processors.py | models.py | tests.py | urls.py | views.py | __init__.py | +---migrations | 0001_initial.py | 0002_auto_20210324_1407.py | 0003_answer.py | __init__.py | \---templatetags poll_extras.py __init__.py -
Django create QR code (Segno) and save to S3
I am seeking to create a QR code upon completion of a profile creation form for a user, and saving the QR image to a FileField. The FileField is also used for a profile_image field which already saves the image from the form to S3. I would like to do the same for the QR code (saving to S3 bucket). Using Segno I am able to generate the QR code. How am I able to create an image of it and save it to S3 via the models.py FileField? My code is as follows for the models.py and views.py files. Any help is appreciated. models.py class Profile(models.Model): def profile_path(instance, filename): return 'profile/{0}/{1}'.format(instance.profile_unique, filename) def qrcode_path(instance, filename): return 'profile/{0}/{1}'.format(instance.profile_unique, filename) #unique profile identification (alphanumeric string to be used on path for qrcode and profile image) profile_unique = models.CharField(max_length=50, default=0) #profile image filefield profile_image = models.FileField(upload_to=profile_path, default='') #qr code filefield qr_code = models.FileField(upload_to=qrcode_path, default='') views.py def add_profile(request): user = request.user userprofile = user.userprofile form = ProfileForm(request.POST or None, request.FILES or None) if form.is_valid(): profile = form.save(commit=False) profile.profile_user_id = user.id profile.profile_unique = get_random_string(8) #segno qr = segno.make_qr('test') qr.save('example.png', scale=4) profile.qr_code = qr profile.save() -
can't access to server. Nginx is not working on docker, Django Project, Daphne, Gunicorn, Redis
I am configuring Nginx for ASGI(with Daphne), WSGI(Gunicorn) as well as Redis and Postgres to deploy Django Project. it was working find but all of sudden the browser is not able to access the server(172.0.0.1:1337) after set up django settings.py for check --deploy with following Nginx logs, I don't think it can cause problems because I just added some configurations in local compose file but compose.prod.yml for production. I didn't set the .sh file yet, every pages that I googled for below messages mention those files for running docker-compose in production. would it be a problem not configuring that .sh file? but It was working even without the file. which part should I check for this problem and any configurations that I need to add? Thanks in advance! if more information needed, let me know. nginx | /docker-entrypoint.sh: /docker-entrypoint.d/ is not empty, will attempt to perform configuration nginx | /docker-entrypoint.sh: Looking for shell scripts in /docker-entrypoint.d/ nginx | /docker-entrypoint.sh: Launching /docker-entrypoint.d/10-listen-on-ipv6-by-default.sh nginx | /docker-entrypoint.sh: Launching /docker-entrypoint.d/20-envsubst-on-templates.sh nginx | 10-listen-on-ipv6-by-default.sh: /etc/nginx/conf.d/default.conf is not a file or does not exist, exiting nginx | /docker-entrypoint.sh: Configuration complete; ready for start up nginx Dockerfile FROM nginx:1.19.0-alpine RUN rm /etc/nginx/conf.d/default.conf COPY nginx.conf /etc/nginx/conf.d Nginx.conf upstream … -
Function in Django Views causing others to throw 404 errors
I have a weird bug where one view: def view_dashboard (request, username): # If no such user exists raise 404 try: user = User.objects.get(username=username) print(user) except: raise Http404 template = 'testingland/dashboard.html' return render (request, template) Is causing others to throw 404 errors when I visit their urls. Note: I get a 404 when I visit the above view's connected url but also when I visit another view's url. For instance, visiting the url associated with this view also throws a 404: def write_description(request): return render(request, 'testingland/write_description.html') Here are my url.py: urlpatterns = [ path('index', views.cafes_home, name='cafes_home'), path('', views.index_2, name='cafes_home'), path('venue/<int:venue_id>/', views.venue_page, name='venue_page'), url('electra/cafe_list/', views.cafe_list.as_view(), name='cafe_list'), url('electra/marker_info/', views.marker_info, name='marker_info'), url('electra/info_box/', views.info_box, name='info_box'), url('electra/new_marker/', views.new_marker, name='new_marker'), url('electra/broadsheet_scraper/', views.broadsheet_scraper, name='broadsheet_scraper'), url('electra/get_cafe/', views.get_cafe, name='get_cafe'), url('add_cafe', views.add_cafe, name='add_cafe'), url('add_description', views.add_description, name='add_description'), url('add_image', views.add_image, name='add_image'), url('add_broadsheet', views.add_broadsheet, name='add_broadsheet'), url('add_broadsheet', views.add_broadsheet, name='add_broadsheet'), path('profile', views.profile, name='profile'), path('users', views.users, name='users'), path('<username>', views.view_dashboard, name='view_dashboard'), url('electra/get_users/', views.get_users, name='get_users'), path('electra/getUserMarkers/', views.getUserMarkers, name='getUserMarkers'), #auth path('signup', views.SignUp.as_view(), name='signup'), path('login', auth.views.LoginView.as_view(), name='login'), path('logout', auth.views.LogoutView.as_view(), name='logout'), #placelist path('write_description', views.write_description, name='write_description'), # path('write_image', views.write_image, name='write_image'), path('broadsheet', views.broadsheet, name='broadsheet'), path('<int:pk>', views.DetailList.as_view(), name='detail_list'), path('<int:pk>/update', views.UpdateList.as_view(), name='update_list'), path('<int:pk>/delete', views.DeleteList.as_view(), name='delete_list'), ] Here is the error: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/dashboard Raised by: testingland.views.view_dashboard -
Speed up counting query in Django
I'm workig with Django2.1 + python3.5 + mysql5.7 Below are some detail infos: db table # models class FbAccountSpendCapHandle(BaseModel): ... class Meta: db_table = 'ka_fb_account_spend_cap_handle' # SQL CREATE TABLE `ka_fb_account_spend_cap_handle` ( `id` int(11) unsigned NOT NULL DEFAULT '0', `account_id` varchar(45) DEFAULT NULL, `account_name` varchar(255) DEFAULT NULL, `type` tinyint(1) DEFAULT '0', `account_status` smallint(4) DEFAULT '0', `submitter` varchar(128) DEFAULT NULL, `submit_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, `status` tinyint(1) DEFAULT '0', `create_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP, `update_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, `is_delete` tinyint(1) DEFAULT '0', `apply_id` varchar(32) DEFAULT NULL, `urgent` tinyint(1) DEFAULT '0', `is_violation` tinyint(1) DEFAULT '0', PRIMARY KEY (`id`), KEY `condition` (`is_delete`,`submit_time`,`submitter`,`status`,`urgent`,`type`,`is_violation`,`account_status`,`apply_id`,`account_name`(191),`account_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 After doing some condition query, I want to count total numbers of all query data. Query detail as below: tem_queryset = FbAccountSpendCapHandle.objects.filter(...) print(tem_queryset.query) SELECT * FROM `ka_fb_account_spend_cap_handle` WHERE (`ka_fb_account_spend_cap_handle`.`is_delete` = 0 AND `ka_fb_account_spend_cap_handle`.`submit_time` BETWEEN "1970-01-01 00:00:00" AND "2021-03-27 16:04:31" AND `ka_fb_account_spend_cap_handle`.`submitter` IN ("a", "b", "c")) ORDER BY `ka_fb_account_spend_cap_handle`.`submit_time` DESC Then I want to get the count of filtered data c = tem_queryset.count() But the query cost about 2s for there being more than 200k queried data. How can I get the count more effectively. Greate thanks -
html div not setting to 100% in django-template
I am new to HTML. I am developing a web application using Django template, I am trying to set the height of the div to the maximum of its parent . The page is as follows: <!DOCTYPE html> <html> <head><title>Billing Lookup</title> <title>Billing Interface</title> </script> <style> html { height: 100%; } body { min-height: 100%; } .main{ height:100%; margin-left:100px; padding-top:10px; padding-left:80px; } </style> </head> <body> <div id="mm" class="main"> {% block content %} {% endblock %} </div> </body> </html> But when i browse this page in chrome or firefox, i see that the body and html is set to 100% covering the whole screen, but the div mm is not showing 100%. Am i missing something here? Screen shot pasted below Note: if i remove this tag <!DOCTYPE html>then I get the height of the div set to 100% which i don't understand. The same happens even in ordinary html file without django env Can anyone please help? Thanks -
Django admin how to create custom view to redirect to another model add view?
I have two models and I want to create a custom view which would redirect to another model add view. My models: class PostAdmin(admin.ModelAdmin): list_display = ['text', 'media', 'send_type', 'created'] class Meta: model = Post admin.site.register(Post, PostAdmin) and class ChannelAdmin(admin.ModelAdmin): list_display = ['title','invite_link', 'account_actions'] def my_custom_view(self, request, *args, **kwargs): !!!!HERE!!! class Meta: model = Channel admin.site.register(Channel, ChannelAdmin) I tried but for it I need self parametr from PostAdmin def my_custom_view(self, request, *args, **kwargs): return PostAdmin.add_view(self, request}) -
Docker: When should we get the variables from vault
I'm trying to use Vault with my Django project which is running on Docker. We had a dispute within the team regarding the place where/when should we get the variables from Vault and allow the application to access them. Let me explain two possible approaches that we discussed but I'm not sure which one is more preferable. When building the docker image, inside the Dockerfile ... RUN get_all_variables_from_vault CMD uwsgi --ini uwsgi.ini Inside the Application(Runtime instead of build-time in above option). This means, Image has been built and we are trying to spawn a container. and once the container is starting-up, we would get all the variables and export them as env variables before actually running the application. Docker image -> spawning the container -> get all variables from vault & export them as env variables -> start application I can understand a few pros/cons of both such as - Suppose vault is down or for some reason we are unable to communicate with Vault API, in that case, 1st option would not even allow us to build an image and hence the previous version of the application would keep running without affecting the end-user. in the 2nd option, it … -
django Testing views works only with a primary key
I am working on a django project. i have build the front end and back-end. now i want to write unit test. i want to test a class based view for creating,deleting and retrieving blog post from url '''path('posts/', Postview.as_view(),name="posts"),''' my Postview view is here: class Postview(views.APIView, LimitOffsetPagination): authentication_classes = [TokenAuthentication, ] permission_classes = [IsAuthenticated, ] def get(self, request, pk=None): if pk: try: query = Post.objects.filter(pk=pk) # print(query) print("in post get") serializer = PostSerializer( query, many=True, context={'request': request}) data = commonPost(serializer.data, request) return Response(data) except: return Response({"message": "No Data found"}) else: query = Post.objects.all().order_by('-id') serializer = PostSerializer( query, many=True, context={'request': request}) data = commonPost(serializer.data, request) return Response(data) def post(self, request, pk=None): if pk: snapshot = Post.objects.get(pk=pk) serializers = PostSerializer( snapshot, data=request.data, context={'request': request}) if serializers.is_valid(): serializers.save() return Response({'error': False}) return Response({'error': True}) else: serializer = PostSerializer( data=request.data, context={'request': request}) if serializer.is_valid(): serializer.save() return Response({'error': False}) return Response({'error': True}) def delete(self, request, pk): try: snippet = Post.objects.get(pk=pk) if snippet.profile.id == request.user.profile.id: snippet.delete() return Response({"error": False}) else: return Response({"error": True}) except: return Response({"message": "No data found for this ID"}) now my unit test def test_post_view(self): client=self.get_client() response=client.get("/api/posts/")# this line self.assertEqual(response.status_code,200) this test gives error of 401!=200 but if i change the url … -
Add Calculated Virtual Column to Django Model Queryset
I'm having a tough time trying to add a virtual column to my django model. My Store model has the following database fields: class Store(models.Model): time_opening = models.TimeField() time_closing = models.TimeField() How can I add an is_open field to the results of my Store queryset? The logic for the field is something like: time_opening <= datetime.now() <= time_closing I have attempted to use annotations in a StoreManager class but I'm not sure how to construct an expression with the logic mentioned above. class StoreManager(Manager): def get_queryset(self): return super().get_queryset().annotate(is_open=??????) I also wrote the raw sql as a backup which returns a virtual column is_open based on the desired logic. For example: SELECT Store.*, True as is_open; In this case, I'm unsure where to use my raw sql. Do I put it in the StoreManager get_queryset function? Do I call Store.objects.raw()? If so, where should I call it? How will it affect built-in django filtering and pagination? -
how to access the foreignkey value from a dict value in django
I am using foreignkey as my dropdown and I wanted to remove the dupicate values from my dropdown so I used query distinct(),but now i am getting dict values and I am not able to access my foreignkey value now. I am getting foreign key ID instead of string. I want to do something like for values in queryset: values.item_name.name my models.py class Requesition(models.Model): item_name = models.ForeignKey(Item,on_delete=models.CASCADE,limit_choices_to={'status':True}) date = models.CharField(max_length=20) quantity = models.IntegerField() requested_by = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) status = models.BooleanField(default=1) approved = models.BooleanField(default=0) def __str__(self): return '%s--%s' % (self.item_name.item_name, self.item_name.specification) my forms.py class Purchase_order(forms.ModelForm): products = forms.ModelChoiceField(queryset= Requesition.objects.all().select_related('item_name').values('item_name').distinct()) class Meta: model = Purchase fields=('__all__') exclude = ('status','select','Total') -
django rest model-view-set list action raise 404 if pass query parameter
if i pass any query parameter get 404 class BusinessViewSet(ModelViewSet): queryset = Business.objects.all() permission_classes = [IsAuthenticated, HasUsernamePermission] filter_backends = [SearchFilter, DjangoFilterBackend, DistanceFilterBackend] ordering_fields = ['name'] pagination_class = LimitOffsetPagination filterset_fields = ['name', 'category'] def get_serializer_class(self): if self.request.method == 'POST': return BusinessCreateSerializer return BusinessSerializer for example if i request /api/businesses/ response code is 200 but if i request /api/businesses/?search=a response code is 404 -
Django Save Unicode unescaped /u into MySQL Database
I'm having a problem when saving the unicode data without unescape /u. The data that got from the client was: {"text": "निम्न प्रश्नोंको हल"} However, when I saved it into the database (MySQL) it's changed into unescape unicode characters: {"text": "\u0928\u093f\u092e\u094d\u0928 \u092a\u094d\u0930\u0936\u094d\u0928\u094b\u0902\u0915\u094b \u0939\u0932"} Both my table and column already using utf8mb4_general_ci collation. I can paste the character into the table manually and it shows the real character. Here's my code: question = Questions() question.data = json.dumps(data, ensure_ascii=False) question.save() It shows fine on the browser, but it makes an issue when I want to export the data into JSON later on. -
Connecting Django Celery Beat to the correct database
I am getting started with celery (4.4.7) using this tutorial. I believe I have set up everything correctly but whenever I run the following command: celery -A myproj beat -l INFO --scheduler django_celery_beat.schedulers:DatabaseScheduler I get the error: django.db.utils ProgrammingError :relation "django_celery_beat_periodictask" does not exist I migrated the DB and so the celery beat tables do exist. This closed issue https://github.com/celery/django-celery-results/issues/22 is exactly the error I am getting, however, what seems to be the solution does not work for me possibly because I don't know how to do it. -
Django PDF generated not download last version
I have a Django view to show a preview of Pdf generated and works well. I have configured an AWS S3 service to save Pdf generated files and overwrite if existing with same name and works well because i have checked and downloaded manually from bucket. When it's generated again it's visualized well in the browser preview but when downloaded it appears the old version. views.py: @login_required() def budget_pdf(request, id=None): budget = get_object_or_404(app_models.Budget, id=id) concepts = budget.concept_budget.all() file = app_pdf.PDF(None, budget, concepts) pdf_file = file.generate_budget() file_name = 'Pto_' + str(budget.brand.client.name) + '_' + str(budget.name) + '_' + str(budget.code) + ".pdf" budget.pdf.save(file_name, ContentFile(pdf_file), save=True) return render(request, 'file.html', {'element': budget}) file.html: <iframe height=100% width="100%" src="{{ element.pdf.url }}" style="min-height: 800px;"></iframe> Anybody could help me please ? Thanks in advance.