Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Overriden Admin Template not importing JS
I have a Django template I am trying to run with my own JS code. So I extended the admin template login in my /templates folder of my app. However, I can confirm the script is there if I go to: http://localhost:8000/static/admin.js But in the source and console log never appear. I don't ever see my script tag either. This is my dir structure: [![directory structure ][1]][1] Here's my template code: {% extends "admin/login.html" %} {% load static %} {% block content %} <h2> hello world! </h2> <p>{% static 'admin.js' %}<p> {% endblock %} <script src="{% static 'admin.js' %}"></script> My settings do have APP_DIRS set to true as well so it should see the template and it does but doesn't put in my script tag. -
How do I write a Django query that matches only the minute field of a DateTime column?
I'm using Django 3.2 and PostGres 9.6. I have this model with a "created" DateTime field ... class PriceQuote(models.Model): ... created = models.DateTimeField(null=False, default=datetime.now) How do I write a Django filter query that includes a clause to match the minute field of the created column? So in the below class PriceQuoteManager(): def get_prices_per_hour(self, item): now = datetime.datetime.now() end_time = now.replace(second = 0, microsecond = 0) start_time = end_time - timedelta(days=1) return PriceQuote.objects.filter( item=item, created__range=[start_time, end_time], xxx=end_time.minute ) I want to replace "xxx" with a clause that says match the minute field of "created" with the minute field of the "end_time" variable. -
add bearer token with post in unit tests Django - ValueError: invalid literal for int() with base 10
I am trying to add a bearer token via posting in the unit tests, the access_token is well generated, but when I pass it i the post request and error is thrown as below : ValueError: invalid literal for int() with base 10: '<bound method TestCase.id of <customers.tests.CustomerProfileTestCase testMethod=test_validate_founder_cant_add_owp>>' Below is my test : def setUp(): user = User.objects.create_user(username='john', email='js@js.com', password='js.sj') client = APIClient() @property def bearer_token(self): """Generate token with bearer""" refresh = RefreshToken.for_user(self) return str(refresh.access_token) def test_create_customer_profile(self, data): """ Create a new customer profile. :param self: Reference to the current instance of the class. :param data: customer profile data. """ token = self.bearer_token self.client.credentials( HTTP_AUTHORIZATION='Bearer ' + token) response = self.client.post( reverse('api:customers:customer-profile-list'), data) assert(response.status, 200) -
DRF Annotate all stores that an author have a book seeling
Currently I'm trying to annotate an information in my Author API: All Stores where that author have a book. I have the following models: class Author(models.Model): name = models.CharField(max_length=100) age = models.IntegerField() class Book(models.Model): name = models.CharField(max_length=300) authors = models.ManyToManyField(Author, related_name='books') class Store(models.Model): name = models.CharField(max_length=300) books = models.ManyToManyField(Book) In my get_queryset method i've tried to do something like: def get_queryset(self): qs = Author.objects.all().annotate( stores=F('books__stores__name') ) return qs but stores return just one name of a store, and not a list of stores. can someone tell me what I'm done wrong ? Edit: my current Serializer: class AuthorSerializer(ModelSerializer): stores = serializers.CharField(max_length=300) class Meta: model = Author fields = ['name', 'age', 'books', 'stores'] -
How do you update user info with an api call to a django/djoser backend?
The djoser endpoint for the user data is /users/ and then the id number of the user. https://djoser.readthedocs.io/en/latest/getting_started.html#available-endpoints But I'm not sure how to get the id number of the user that's currently logged in so the api call can have that id number at the end. I'm able to get their token but not their actual id number. Any ideas on how to do that? I took a screenshot of the code below screenshot -
Django - AttributeError: module 'environ' has no attribute 'ENV'
Installed Python 3.9 on Windows 10. Also installed Django 3.2 Django-environ 0.8. But I don't know why this raise an error when I tried to run python manage.py runserver My code: import environ from pathlib import Path env = environ.ENV(DEBUG=(bool, False)) The error: AttributeError: module 'environ' has no attribute 'ENV' -
Recreating bootstrap cards row layout with tailwind in django
ASK I'm trying to recreate bootstrap cards row layout with Tailwind within django framework BLOCKER However the tailwind attempt results in below index.html -- bootstrap {% extends 'base.html' %} {% block title %}Home{% endblock title %} {% block content %} <div class="py-2"> <div class="row"> {% for t in object_list %} <div class="col-md-3"> <div class="card mb-4 box-shadow bg-green-500"> <div class="card-body"> <h2 style="font-size:18px;font-weight:bold;min-height:42px;"><a class="text-dark" href="#"> {{t.currency|truncatechars:50}}</a></h2> <div class="d-flex justify-content-between align-items-center"> <small class="text-muted">{{t.country|truncatechars:25}}</small> </div> </div> </div> </a> </div> {% endfor %} </div> {% endblock content %} index.html -- tailwind {% extends 'base.html' %} {% block title %}Home{% endblock title %} {% block content %} <div class="p-10 "> <div class="max-w-sm rounded overflow-hidden shadow-lg"> {% for t in object_list %} <div class="px-6 py-4"> <div class="font-bold text-xl mb-2">{{t.country}}</div> <p class="text-gray-700 text-base"> {{ t.currency }} </p> </div> {% endfor %} </div> </div> {% endblock content %} -
JavaScript help for responsive webapp
I know I might get some flack for this, but I'm basically looking for someone to spoon feed me with some javascript instructions for a web app I'm working on. I have no prior JS knowledge. I'm using Jinja2 template to render the webapp. The index page rengers out a list of divs which contain information about particular events. Users can join these events. This is done by sending a post request to the Django Server with the users name and the event ID. Can someone help me out with the JS code creates a pop-up display when a user clicks "join" button on a particular event. <div class="container" id="container"> {% for event in data %} <div class="event"> <div class="sport"> <h2>{{ event.description }}</h2> </div> <div class="venue"> <p> <span class="title">Creator:</span> {{ event.creator }}</p> </div> <div class="time"> <p> <span class="title">Date and Time:</span> {{ event.time }}</p> </div> <div class="venue"> <p> <span class="title">Venue:</span> {{ event.venue }}</p> </div> <div class="participants"> <p> <span class="title">Participants:</span> {{ event.participants }}</p> </div> <div class="join-now"> <a><h3 id="{{ event.id }}" class="join-now-button">Join</h3></a> </div> <div class="see-participants"> <a> <h3>See Participants</h3> </a> </div> </div> <div class="join-form"> <form action=""> <label for="">{{ event.id }}</label> <p><span class="title">Your Name:</span></p><input type="Name"> <br><br> <div class="join-now"> <a href=""> <button> <h3>Join</h3> </button> </a> </div> … -
stripe integration on Django project TypeError
I am new to Django and Stripe API. I am following the Stripe document and I copied the code from the document to my view.py file: this is my views.py file from django.shortcuts import render,redirect from django.conf import settings from django.urls import reverse from django.views import View import stripe stripe.api_key = settings.STRIPE_SECRET_KEY class Create_checkout_session (View): def post(self, request, *args, **kwargs): DOMAIN = "http://127.0.0.1:8000" checkout_session = stripe.checkout.Session.create( line_items=[ { # Provide the exact Price ID (e.g. pr_1234) of the product you want to sell 'price': 'price_id', 'quantity': 1, }, ], payment_method_types=[ 'card', ], # mode can be subscription, setup, payment mode='payment', success_url=DOMAIN+'/success/', cancel_url=DOMAIN+'/cancel/', ) return redirect(checkout_session.url, code=303) This is my urls.py in payment app: from django.urls import path, include #import views.py from . import views app_name ='payment' #set urls for the app urlpatterns = [ path('create-checkout-session/',views.Create_checkout_session, name='create-checkout-session') ] The error message I have is when I render this page, I have: TypeError at /create-checkout-session/ init() takes 1 positional argument but 2 were given Request Method: GET Request URL: http://127.0.0.1:8000/create-checkout-session/ Django Version: 3.2.8 Exception Type: TypeError Exception Value: init() takes 1 positional argument but 2 were given Exception Location: /Users/hannah/Desktop/TDMock/venv/lib/python3.9/site-packages/django/core/handlers/base.py, line 181, in _get_response Python Executable: /Users/hannah/Desktop/TDMock/venv/bin/python I put the stripe secret … -
Django Rest Framework Forbidden when i send post request
I am making a website with django rest framework backend and a react frontend but when i use axios to send a post request to /products it sends a 403 forbidden error this is the views file @api_view(['GET', 'POST']) def products(request): if request.method == 'GET': products = Product.objects.all() serializer = ProductSerializer(products, many=True) return Response(serializer.data) elif request.method == 'POST': serializer = ProductSerializer(data=request.data) print(request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) this is how i send the request in react: const handleSave = () => ( axios.post('/products', getInputData()).then((response) => (console.log(response))) ); this is my settings file in django: ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', 'rest_framework', 'API', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ORIGIN_ALLOW_ALL = False CORS_ORIGIN_WHITELIST = ( 'http://localhost:3000', ) -
How to add a custom action for the same route as default one in a ViewSet
Suppose, we have a ViewSet class: class SomeViewSet(viewsets.ViewSet): def create(self, request): pass def custom_action(self, request): pass and we register SomeViewSet as follows: some_router = DefaultRouter() some_router.register(r'some-route', AuthenticationViewSet, basename='some-name') So, now we have the SomeViewSet with the standard action create, that will be accesible with the route some-route/ using POST HTTP method. The question is how to configure the custom_action action to be accesible by the same route as a standard create action (some-route/) with PUT HTTP method. -
Why the 'and' operator isn't working in the Django template?
What's supposed to be wrong in the following if-else statement in my template? {% if rp.package.patient_type != "CASH" and rp.realization.cash == True %} N/A {% else %} {{rp.realization.deficit_or_surplus_amount}} {% endif %} Even when the patient type is Cash, it displays N/A. Where am I going wrong here? -
Fullcalendar v5 only renders one event tip
I´m trying to render some events in v5 fullcalendar. This is my code: document.addEventListener('DOMContentLoaded',function(){ var cUI= document.getElementById('calendar'); var c= new FullCalendar.Calendar(cUI,{ themeSystem: 'bootstrap', headerToolbar:{ left:'prev,next today', center:'title', right:'', }, events:[ {% for v in vacation %} { {% if v.id_cause.cause_name == 'Vacations' %} backgroundColor : 'blue', borderColor : 'blue', {% else %} backgroundColor : 'darkgreen', borderColor : 'darkgreen', {% endif %} textColor : 'gray', title:"{{ v.startT }} - {{ v.endT }}", start: "{{ v.startD | date:'Y-m-d' }}", end: "{{ v.endD | date:'Y-m-d' }}", description:"{{v.id_cause.cause_name}} {{v.cause_text}}", }, {% endfor %} ], {% comment %} eventDidMount: function(info) { var tooltip = tippy('.fc-event-title-container',{ content: info.event.extendedProps.description, placement: 'top', interactive: true, }); }, {% endcomment %} }); c.render(); c.setOption('locale','en'); }); It renders the calendar and tips, however it repeats the same tip for all events, but colors for different cause_names shows different, so I don´t get the point it renders all events with their data correctly but tips fails. I´m on django 3 btw. Maybe rollback to previous fullcalendar version with eventRender, instead eventDidMount? Thanks for the help -
JSONDecodeError while working with websockets
I'm learning to work with WebSockets. I'm using Django as server-side and react at the client-side. I'm able to connect and send an object to the backend but unable to receive massage on the frontend side. I'm sharing my code. Please me my flaws and a perfect way to do the basic setup of sockets on the frontend and backend. Thank You. django-python import json from channels.generic.websocket import WebsocketConsumer class ProjectConsumer(WebsocketConsumer): def connect(self): print("HEY HEY HEY HEY") self.accept() def disconnect(self, close_code): pass def receive(self, text_data): print("Reciasha",text_data) text_data_json = json.loads(text_data) # message = text_data_json['message'] message =text_data print("Hey",message) self.send(text_data=json.dumps({ 'message': message })) React-js export const WebSocketTest = () => { var ws = new WebSocket("ws://localhost:8000/ws/projects/"); ws.onopen = function() { // Web Socket is connected, send data using send() const msg = { "firstName": "Jane", "lastName": "Doe", } ws.send(msg); alert("Message is sent..."); }; ws.onmessage = function (evt) { const data = JSON.parse(evt.data); // var received_msg = evt.data; console.log(evt) console.log("data",data) console.log("received_msg",data["message"]) alert("Message is received..."); }; ws.onclose = function() { // websocket is closed. alert("Connection is closed..."); }; } Right now I'm facing the below error: WebSocket HANDSHAKING /ws/projects/ [127.0.0.1:43012] HEY HEY HEY HEY WebSocket CONNECT /ws/projects/ [127.0.0.1:43012] HTTP GET /api/project-viewset/ 200 [0.11, 127.0.0.1:43008] Reciasha … -
Cannot insert an entity along with it's foreign key in django/djangorestframework
I have the following models in my application: class User(models.Model): name = models.CharField(max_length=100) birth_date = models.DateField() address = models.CharField(max_length=200) class Device(models.Model): description = models.CharField(max_length=200) location = models.CharField(max_length=200) max_energy_consumption = models.FloatField() avg_energy_consuumption = models.FloatField() user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) A user can have multiple devices, hence the foreign key user in the Device class. These are my serializers: class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = '__all__' class DeviceSerializer(serializers.ModelSerializer): user = UserSerializer(read_only=True) class Meta: model = Device fields = '__all__' I am using a default ModelViewSet for CRUD operations: class UserViewSet(ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer class DeviceViewSet(ModelViewSet): queryset = Device.objects.all() serializer_class = DeviceSerializer In my database, the devices table has a user_id column, like it should. When I open the Django API in the browser, I see this: In the POST form, there is no field for user_id. Shouldn't it be one? How am I supposed to add a device through a request and specify which user it belonges to? Like this it just puts null in the user field, which is not what I want. I want to specify to a device which user it belonges to at creation. -
Include React app inside MPA Django Website
How do you integrate a React application into Django MPA website? The website has multiple pages. One of the pages is where changes intensive react app should be placed in. The rest pages use vanilla js. React app and rest pages would share same database, but the functionality of the react app is mostly seperate from the rest webpage. It is like if you had a game/player/some tool inside a website that you can load. My most fears is about js and react conflicts. -
How do I use a postgresql function result in a Django template?
I'm quite new to Django so I suspect I'm missing something simple. I've used Django to build a website that features "regular" pages as well as a data-entry, display, update and delete pages in a back-end section of the website that requires a login to access. All of that was easy. I've also used Django's template inclusion feature and, for what I've needed so far, it seems to work fine. I now have a requirement to use a postgresql function to dynamically generate a central portion of a webpage and include that in the template. Basically, if a page is called "abc" then I need to do something like textfield = myfunction('abc') where myfunction would generate the equivalent of a static template stored in a folder. I understand (I think) that the template inclusion content can be contained in a variable. What I'm missing is how to get the results of the postgresql function into that variable in the template. I'm assuming that I need to put this logic in the model but I haven't been able figure out how to do that. Any help or advice would be greatly appreciated. Thanks! -
Heroku Server Keeps Crashing
I deployed a Django website on Heroku and sometimes I get lots of H10 (App crashed) messages in the log. Sometimes it ends up in some sort of a crash loop and I have to go in and restart the dyno manually. I'm running hobby dyno and that doesn't allow me to scale up or add redundancy options, but I want to find out what is causing the app to crash. The app deploys fine and starts as it should, the problem occurs in runtime when its serving client requests. In the Heroku log I only see very basic info, very similar to this example from Heroku support: "heroku[router]: at=error code=H10 desc="App crashed" method=GET path=/ host=myapp.herokuapp.com fwd=17.17.17.17 dyno= connect= service= status=503 bytes=" It would useful to understand where the app crashed so that I can find and solve the root cause. (or could the problem be lack of resources at Heroku?) Thank you in advance! -
targeting id on a loop to toggleClass with Jquery
I'm trying to make it so when a user presses a button, an element inside the button changes class. I managed to do that when I have a clear id for button. <button id="buttonId"><i class="class1"></i></button> <script> $(document).ready(function(){ $("#buttonId").click(function(){ $(this).find('i').toggleClass('class2').toggleClass('class1'); }); }); </script> Now I need to create a sequence of buttons, and for that I've set the id like this: {% for i in X %} <button id="{{i.id}}"><i class="class1"></i></button> {% endfor %} However I don't know how I can reference i.id inside the function. The example below didn't work. $(document).ready(function(){ $("{{i.id}}").click(function(){ $(this).find('i').toggleClass('class2').toggleClass('class1'); }); }); How do I find the id? -
no such column: Homepage_goods.number_text
I have a problem of displayed a model text in index.html This is code of views.py class IndexView(generic.ListView): template_name = 'Homepage/index.html' model = Goods context_object_name = 'goods' def description(self): return self.description_text def price(self): return self.price_text def number(self): return self.number_text This is code of html(index.html) {% for good in goods %} <h3 class="numbers">{{good.number_text}}</h3> {% endfor %} -
Django js JQuery Basket_adding
Ребят, помогите пожалуйста, я новичок в Django, JS. В общем, создаю корзину. Добавил JQuery, отображение нормальное было (добавлялось). Потом уже создавал бек: создал модель ProductInBasket, во views.py сделал функцию. Но, теперь, когда нажимаю на кнопку "В корзину" мне показывает вот это: enter image description here То есть, после каждого обновления страницы, добавляется +1. Вот... Сайт, в общем, не выводит. Не знаю, в чём проблема, такой вот странный затык... Помогите, пожалуйста) Вот код: JS: $(document).ready(function() { var form = $('#form-buying-product'); console.log(form); form.on('submit', function(e){ e.preventDefault(); console.log('123'); var nmb = $('#number').val(); console.log(nmb); var submit_btn = $('#submit_btn') var product_id = submit_btn.data("product_id") var product_name = submit_btn.data("name") var product_price = submit_btn.data("price") console.log(product_id); console.log(product_name); console.log(product_price); var data = {}; data.product_id = product_id; data.nmb = nmb; var csrf_token = $('#form-buying-product [name="csrfmiddlewaretoken"]').val(); data["csrfmiddlewaretoken"] = csrf_token; var url = form.attr("action"); console.log(data); $.ajax({ url: url, type: 'POST', data: data, cache: true, success: function (data) { console.log("OK"); error: function(){ console.log("error") } }) $('.basket-items ul').append('<li>'+product_name+', ' + nmb + 'шт. ' + 'по ' + product_price + 'грн ' + '<button style="background-color: #ff0000; color: white; z-index: 99999 !important;" type="button" class="delete-item btn close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>' +'</li>'); }); function showingBasket() { $('.basket-items').removeClass('hidden'); } $('.basket-container').on('click, hover', function(e){ e.preventDefault(); showingBasket; }) $('.basket-container').mouseover(function(){ showingBasket(); }) $('.basket-container').mouseout(function(){ showingBasket(); … -
Django not loading staticfiles but sucessfull collectstatic
i got a problem, i need to switch from develop to productive, i do sucessfully collectstatic and switch debug to False, but when i run my server, on local, docker run or in google microservices the static folder wont load any files so i got only plain html, unless y use --insecure command. this are my relevant settings.py lines: DEBUG = True ALLOWED_HOSTS = ['*'] TATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'estandar_diseno/static'), ) STATIC_ROOT = os.path.join(BASE_DIR, 'production_static') DATA_UPLOAD_MAX_MEMORY_SIZE = 5242880 GS_CREDENTIALS = service_account.Credentials.from_service_account_file( os.path.join(BASE_DIR, 'credencial.json')) DEFAULT_FILE_STORAGE = 'storages.backends.gcloud.GoogleCloudStorage' GS_PROJECT_ID = 'green-carrier-xxxxx' GS_BUCKET_NAME = 'inversiones-admision' UPLOAD_ROOT = 'reportes/' MEDIA_ROOT = 'reportes' MEDIA_URL = 'https://storage.googleapis.com/{}/'.format(GS_BUCKET_NAME) if not DEBUG: import mimetypes mimetypes.add_type("application/javascript", ".js", True) Folder structure: So its supose that bucket with mediafiles only hold upload files, from users, and have all the static files on the docker container and then upload to google microservices, but the problem i got is even on local as i said doesnt work, im missing something? collectstatic just work well, i get copied all the files. -
Django index value of array
I am sending an array of arrays a post request through $ajax ie: [[1, "25, 25, 25", "pounds", "exercise note 1"],[2, "", "No Weight", "note 2"]] My ajax: $.ajax({ type: 'POST', url: '', dataType: 'json', data:{ csrfmiddlewaretoken: csrftoken, targets:JSON.stringify(targets), // notes:notes, // time:time, // rating:rating }, success: (res)=>{ console.log(res) }, error: (error)=>{ console.log(error) } }) In django, when I print(request.POST), I get 'targets[0][]':[1, "25, 25, 25", "pounds", "exercise note 1"], 'target[1][0]':[2, "", "No Weight", "note 2"]. I have tried JSON.stringify([[1, "25, 25, 25", "pounds", "exercise note 1"],[2, "", "No Weight", "note 2"]]) and I get back 'targets': ['[[2,"25, 25, 25","Pounds","note 1"],[1,"","NoWeights","note 2"]]'], I've also tried: ts.push(t) django returns: 'targets[]': ['[2,"25, 25, 25","Pounds","note 1"]', '[1,"","NoWeights","note 2"] which is what I want. But when I do targets = request.POST.getlist('targets[]) for target in targets: print(target[2]) -->I want either "25, 25, 25" or , "" But all I get is , and when I print(len(target)) the first array returns 34. Why? How do I get the strings? What am I doing wrong? I want to assigned each index in the target array to a varible so I can save to the database -
Django cannot connect to running postgres docker container
I am surprised that I cannot get this to work, as I have run a django applications with a postgres DB in docker containers multiple times, however, this time on my Linux machine the django application cannot connect to the postgres docker container, whereas on my Mac the setup works without a problem. I am getting the standard error: django.db.utils.OperationalError: could not connect to server: Host is unreachable Is the server running on host "postgresdb" (172.27.0.2) and accepting TCP/IP connections on port 5432? The postgres container is running and should be reachable. I check the IP address of the docker container and it seems correct. My docker-compose file looks like this: version: "3.8" services: app: container_name: data-management restart: always build: ./ ports: - '3000:3000' links: - 'postgresdb' volumes: - ./:/usr/local/share/src/app env_file: - .dev.env postgresdb: container_name: be-postgres restart: always image: postgres:13.4-alpine ports: - '5432:5432' volumes: - postgres-db:/var/lib/postgresql/data env_file: - .dev.env volumes: postgres-db: The configurations are stored in an environment file, which is used in both containers to avoid any mismatches. POSTGRES_PASSWORD=devpassword123 POSTGRES_USER=devuser POSTGRES_SERVICE=postgresdb POSTGRES_PORT=5432 POSTGRES_DB=data_management The django DB settings are as standard as they could be: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'HOST': os.environ['POSTGRES_SERVICE'], 'NAME': os.environ['POSTGRES_DB'], 'PORT': os.environ['POSTGRES_PORT'], 'USER': os.environ['POSTGRES_USER'], … -
Django: print latest download date and how many new entry since last download
In my app I've created a working function to dowload all the user information in my database. In my html page I'd like also to add the date of the latest time that the csv file was downloaded and how many new profile where added since the last download. I've thought to use the iformation stored in the name file to do so but I'm getting this error name 'file_name' is not defined account.views @login_required def download_csv(request): response = HttpResponse(content_type='text/csv') profile_total = Information.objects.all().count() profile_csv_date_donwload = str(datetime.today().strftime("%d-%m-%Y")) file_naname = + profile_csv_date_donwload + str(profile_total) +'.csv' response['Content-Disposition'] = 'attachment; filename=' + file_naname writer = csv.writer(response, delimiter=';') info = Information.objects.all() writer.writerow(['first_name', 'last_name', 'gender', 'birthdate']) for i in info: writer.writerow([i.first_name, i.last_name, i.gender, i.birthdate]) return response donwload.views from account.views import download_csv def download_page(request): profile_total = Information.objects.all().count() latest_d_csv = file_name[0:10] latest_n_csv = file_name[11:] new_profile = profile_total - int(latest_n_csv) context = { 'profile_total': profile_total, 'latest_d_csv': latest_d_csv 'latest_n_csv': latest_n_csv 'new_profile': new_profile } return render(request, 'page/download.html', context) html <div class="col-md-8"> <div class="row gutters-sm"> <div class="col-sm-6 mb-3"> <div class="card h-100"> <div class="card-body"> <h6 class="d-flex align-items-center mb-3">Profile CSV</h6> <br/> <small>Profile in Database: {{ profile_total }}</small> <br/> <small>Latest Download: {{ latest_d_csv}}</small> <br/> <small>New Profile: {{ new_profile }}</small> </div> </div> </div>