Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Hardcode the value of a child class model field to be = to a field value in its parent
In a Django model, I would like to force a field of a child class to have a fixed value inherited from of a field of its parent. E.g.: from django.db import models class Entity(models.Model): class Type(models.TextChoices): Natural = ("Natural", "natural") Juridical = ("Juridical", "juridical") entity_type = models.CharField( max_length=9, choices=Type.choices, default=Type.Natural, ) class Person(Entity): person_type = Entity.Type.Natural # <--- forcing it to be 'Natural' from parent class ... I want to create such person_type field and forcing its value to be 'Natural' for each person object created using the Person class. This field can then be displayed in the admin, but the user must not have any kind of option to modify it. Same in the DB, ideally. I found nothing which relates to this idea in the doc: https://docs.djangoproject.com/en/4.1/ref/models/fields/ and I'm not able to apply this answer to set the value of the person_type field: https://stackoverflow.com/a/68113461/6630397 -
select not creating category entry in django database
I need to make it so that the select from the form is displayed in the database, None appears in its place in the database everything is added except categories and stocks I was told that I need to add value to option, but nothing happened to me what's wrong Here is my views.py : def create_product(request): categories = Category.objects.all() stock = Stock.objects.all() if request.method == 'POST': product = Product() product.title = request.POST.get('title') product.category = Category.objects.get(id=request.POST.get('category')) product.price = request.POST.get('price') product.user = request.POST.get('user') product.amount = request.POST.get('amount') product.stock = request.POST.get('stocks') product.user = request.user product.save() return redirect('index') return render(request, 'main/create.html', {'categories':categories,'stocks':stock}) Here is my models.py : class Product(models.Model): title = models.CharField(verbose_name="Название товара", max_length=250) categories = models.ForeignKey(Category, on_delete=models.CASCADE, blank=True, null=True) price = models.IntegerField(verbose_name="Цена") user = models.ForeignKey(get_user_model(),on_delete=models.CASCADE,related_name='products') amount = models.CharField(max_length=250,verbose_name='Количество') user = models.ForeignKey(User, on_delete=models.PROTECT) stock = models.ForeignKey(Stock, on_delete=models.PROTECT, blank=True, null=True) def get_absolute_url(self): return reverse("post_detail",kwargs={'pk':self.pk}) class Meta: verbose_name = 'Товар' verbose_name_plural = 'Товары' def __str__(self): return self.title My create template : <div class="" style="width: 600px; margin:0 auto; transform: translate(0, 10%);"> <h1 class="display-6">Создайте товар</h1> <form action="{% url 'create_product' %}" method="POST" class="form-control" style="background:rgba(0, 0, 0, 0.1); height: 500px;"> {% csrf_token %} <div class="mb-3"> <label for="exampleFormControlInput1" class="form-label">Название</label> <input type="text" class="form-control" id="exampleFormControlInput1" placeholder="Название товара" name="title"> </div> <div class="mb-3"> <label for="exampleFormControlInput1" … -
pipenv pytest ignores source changes or uses cached source?
I have a Django 4.0.6 project, Python 3.9.15, Ubuntu 22.10, pipenv 2022.10.25, pytest 7.1.2 The test output was cached somewhere and now any modification is ignored unless I delete the method. The steps I performed: Run the test: pipenv run pytest src/some/path/models.py The test fails, showing the correct error in traceback. Modify the method body. Run the test again. The test fails again, BUT the traceback shows old code, unmodified. Removing the method solves the problem, but any modification made to the method source makes it appear again in traceback, UNMODIFIED. Does pipenv/pytest/whatever cache the source somewhere? pipenv run pytest src/some/path/models.py --cache-clear did not help. As well as removing the .pytest_cache/. I tried removing the venv/some/path/__pycache__/models.cpython-39.pyc file (and all compiled *.pyc files in venv) But nothing seem to help. The same traceback appears every time I run tests. -
'int' object has no attribute 'save' in django
I have a value in a database on phpmyadmin and I want to change this value by a new calculated value. The function save() doesn't work and the error tells me that it's because it's an interger. I don't know how to solve this problem. def DeleteBulle (request, id_bulle): #suppression de la bulle par l'id id_bulle param = Bulles.objects.get(pk=id_bulle) #param.delete() #adaptation du champ "nombre de bulle" dans la table "site" site=param.id_site print('site', site) compte=Bulles.objects.filter(id_site=site).count() print('nombre bulle avec site identique', compte) nbrbulle=Bulles.objects.get(pk=id_bulle).id_site.nombre_bulles nbrbulle=compte nbrbulle.save() #réussite print("Bulle supprimée") return redirect('api_bulles_frontend') I don't know how to solve this problem. Thank you for your help. -
docer-compose.yml in Django project: environment variables are not created from the .env file
My docker-compose.yml: version: '3.8' services: web: build: ./app command: python3 manage.py runserver 0.0.0.0:8000 volumes: - ./app/:/usr/src/app/ ports: - 8000:8000 env_file: - .dev.env my Dockerfile in ./app: FROM kuralabs/python3-dev WORKDIR /usr/src/app ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # RUN pip install --upgrade pip COPY ./requirements.txt . RUN pip3 install -r requirements.txt COPY . . My file '.dev.env': ALLOWED_HOSTS='localhost 127.0.0.1' DEBUG=1 SECRET_KEY='django-insecure-...' I run the project with the commands: $docker-compose build $docker-compose up -d I get variables in settings.py: load_dotenv() print(f'Environment: {os.environ}') my variables from the '.dev.env' file are not in the list of environment variables. Please help me understand why '.dev.env' variables don't get into the environment? -
Django incomplete migration of table with multiple foreign keys
Django version: 4.1.2 After heaving the following table defined in the model: class Tasks(models.Model): name_text = models.CharField(max_length=200) duration_int = models.IntegerField(default=1) ... the next two tables have been defined: class Metiers(models.Model): name_text = models.CharField(max_length=50) ... class TasksProperties(models.Model): task = models.ForeignKey(Tasks, on_delete=models.CASCADE, related_name='task_relation') metier = models.ForeignKey(Metiers, on_delete=models.CASCADE, related_name='metier_relation') ... doing the migration, the metier is not created inside the SQL table, but the rest: class Migration(migrations.Migration): dependencies = [ ('simo', '0009_alter_specialdays_day_date'), ] operations = [ migrations.CreateModel( name='Metiers', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name_text', models.CharField(max_length=50)), ], ), migrations.CreateModel( name='TasksProperties', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('workload_mh', models.IntegerField(default=8)), ('task', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='simo.tasks')), ], ), ] Is there any reason, why metier is not taken into account? -
Need to show result on the same page - Django
I'm creating a password generator app. The app is working and stores the value on db. The problem is whenever I refresh, the form resubmits and takes the previous value and stores. Also, I want to show the email and password on the same page. Whenever I refresh, I want to show an empty form with empty fields. Views.py def home(request): if request.method=='POST': inputemail = request.POST.get('InputEmail') gen = ''.join(random.choices((string.ascii_uppercase+string.ascii_lowercase+string.digits+string.punctuation), k=10)) newpass = Item(email=inputemail,encrypt=gen) newpass.save() return render(request,'home.html',{"gen":gen}) return render(request,'home.html',{}) Home.html <form method = 'post' id='pass-form' > {% csrf_token %} <div class="mb-3"> <label for="exampleInputEmail1" class="form-label">Email address</label> <input type="email" class="form-control" name="InputEmail" > <div id="emailHelp" class="form-text">We'll never share your email with anyone else.</div> </div> <button type="submit" name = "submit" class="btn btn-primary">Generate Password</button><br><br> </form> <div class="mb-3"> <label for="exampleInputPassword1" class="form-label">Generated Password</label> <input type="text" id="InputPassword" name = "genpassword" value = {{gen}} > </div> Urls.py urlpatterns = [ path('',views.home,name='home'), ] -
When I filter I need to request.GET.value to be selected
I have to filter some data so I need to use a select field but when I submit the form the result disappears. I have to selected the value that is choice previous ` <label class="text-secondary">Discount Type</label> <select name="discount_type" class="form-control" > <option value="" class="text-center" >Select Type</option> {% for i in type %} <option {% if i.0 == request.GET.status %} selected {% endif %} value="{{ i.0 }}" >{{ i.1 }} </option> {% endfor %} </select>` -
Django Heroku deployment not serving static image files with Whitenoise
My css and js static files are working but my images are not loading. whitenoise==6.2.0 works in development but not with debug off.. MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', ] DEBUG = False STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage" django_heroku.settings(locals()) URLS.PY if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) some template {% load static %} <center><img class="rounded" src="{% static 'images/sm_logos/about-1.png/'%}" style="height:300px; width:300px;"></center> C:\Users\Boss Chris\Desktop\Projects\CBlog\CBlog_project\blog\static\images\sm_logos\about-1.png appreciate your help.. been at this since yesterday and maxed out on pushups.. cant do anymore.. tried putting my static files in S3 too.. doesn't work but i'll try again tmrw if there's no solution -
Search in multiple models in Django
I have many different models in Django and I want to search for a keyword in all of them. For example, if you searched "blah", I want to show all of the products with "blah", all of the invoices with "blah", and finally all of the other models with "blah". I can develop a view and search in all of the models separately, but it's not a good idea. What is the best practice for this situation? -
DjangoCMS - Render database data to html
I'm testing out the DjangoCMS but I cannot understand how to create custom plugins that enable rendering data out of the database. I'd like to create a plugin that shows all the users for example but I can't understand how to pass the data into the HTML file. I followed the DJangoCMS documentation to create a custom plugin that shows the guest name, I've already tried to add users = User.objects.all() and then pass it to the render function but I receive an argument exception because the render function does not allow so many arguments, so what's the approach in DJangoCMS? models.py from cms.models.pluginmodel import CMSPlugin from django.db import models class Hello(CMSPlugin): guest_name = models.CharField(max_length=50, default='Guest') cms_plugins.py from cms.plugin_base import CMSPluginBase from cms.plugin_pool import plugin_pool from django.utils.translation import gettext_lazy as _ from django.contrib.auth.models import User from .models import Hello @plugin_pool.register_plugin class HelloPlugin(CMSPluginBase): model = Hello name = _("Hello Plugin") render_template = "hello_plugin.html" cache = False def render(self, context, instance, placeholder): context = super().render(context, instance, placeholder) return context -
Additional borders and wrong display when using class="d-none d-sm-block d-md-block" bootstrap
I need to hide some of the columns of my table on mobile. I use d-none d-sm-block d-md-block to do that on small and medium screen sizes. This is my code: <table border="1px" class="table table-hover"> <thead class="thead-dark"> <tr> <th class="d-none d-sm-block d-md-block">Fund</th> <th>Why them</th> <th>How to donate</th> </tr> </thead> {% for fund in funds_list %} <tr> <td class="d-none d-sm-block d-md-block"> <a href={{ fund.url }} target="_blank" rel="noopener noreferrer">{{ fund.name }}</a></td> <td> {{ fund.description|safe }}</td> <td> <a href={{ fund.bank_details }} target="_blank" rel="noopener noreferrer" class="btn btn-primary stretched-link">Go to website</td> </tr> {% endfor %} </table> When I'm not additing these classes, my table looks fine: However, after I add this class="d-none d-sm-block d-md-block", some strange border appears around a column I want to hide: -
Django rest-framework , Serializer returning assertion Error
I'm extending my current model to have some common properties from other base classes. Before extending the model, everything was working fine. But after extending, I'm getting the assertion error while performing put and post Operation. I tried my best to resolve it by my own. But not getting where it is going wrong. Can anyone help me on this? Please find my model and serializers below. basemodel.py from django.db import models class BaseModel(models.Model): created_at=models.DateTimeField(auto_now=True) updated_at=models.DateTimeField(auto_now=True) class Meta: abstract = True softdelete.py from django.db import models class SoftDeleteModel(models.Model): is_deleted = models.BooleanField(default=False) def delete(self): self.is_deleted = True self.save() def restore(self): self.is_deleted = False self.save() class Meta: abstract = True movies.py from django.db import models from cinimateApp.models.comman.softdelete import SoftDeleteModel from cinimateApp.models.comman.basemodel import BaseModel # Create your models here. class Movies(SoftDeleteModel,BaseModel): name=models.CharField(max_length=250) description=models.CharField(max_length=250) active=models.BooleanField(default=False) def __str__(self): return self.name movieSerializer.py #Model Serializer from rest_framework import serializers from cinimateApp.models.movies import Movies class MovieSerializer(serializers.ModelSerializer): class Meta: model = Movies fields = '__all__' # fields=['id', 'name', 'description', 'active'] # exclude=['name'] # field Level Validation def validate_name(self,value): if(len(value)<3): raise serializers.ValidationError('name is too short') return value #Objectlevel validation def validate(self,data): if(data['name']==data['description']): raise serializers.ValidationError('name and description should be different') return #custome serializer field name_length=serializers.SerializerMethodField() def get_name_length(self,object): return len(object.name) viws.py from … -
Combining annotation and filtering in Django for two different classes
Hi I am trying to query and count marketplaces for every infringement only for the logged in user. Essentially trying to combine these two. mar_count = Marketplace.objects.annotate(infringement_count=Count('infringement')) inf=Infringement.objects.filter(groups__user=request.user) I found a below example but this is for the same class. I have two separate classes. I am a beginner. swallow.objects.filter( coconuts_carried__husk__color="green" ).annotate( num_coconuts=Count('coconuts_carried') ).order_by('num_coconuts') -
Logic for different leave types in django rest framework for Leave management system
Actually I'm working on Hrms application in django rest framework. I've created employee details module now next part is leave management system. Actually my company policy has different leave policies like cl,sl,ml,compo off, and permissions.I'm unable to understand how to make the logic for it and and don't know where to write the logic in serializers or views? Since a newbee i find somewhat difficult. Also when a employee apply a leave it should be requested to T.L. and then should be visible to hr and manager. T.l would give permission and it all should be in application and also in email process. How to make request and approval in rest api also how to send mail using django rest api? Can anyone guide me This is the code tried class LeaveRequest(models.Model): options = ( (Cl', 'cl), (Sl', 'sl), (Ml, 'ml), (Compoff,compoff) ) choices = ( ('Approved', 'Approved'), ('Rejected', 'Rejected'), ('Pending', 'Pending'), ) user = models.ForeignKey(User, related_name="leaverequest_user", on_delete=CASCADE) employee = models.ForeignKey(Employee, related_name="leaverequest_employee", on_delete=CASCADE) type = models.CharField(choices=options, max_length=50) status = models.CharField(choices=choices, max_length=50) text = models.CharField(max_length=500) date_time = models.DateTimeField(auto_now_add=False, -
what is charset=ibm037 in http
I am new to bug bounty & StackOverflow. I watched a presentation called ''WAF Bypass Techniques Using HTTP Standard and Web Servers ' Behavior - Soroush Dalili." I need help understanding something about IBM037 and IBM500 encoding. What is 'charset =ibm037' What is 'boundary=blah' Does anyone know any encoder for IBM037 & IBM500? I googled it, but I couldn't find anything. -
How to convert string with any date format to %m/%d/$Y in Python
I have a csv with with dates. The dates have inconsistent formatting and I want it all to change to mm/dd/yyyy upon importing. Is there a way to do it? I know about strptime but that requires a second argument for the format of the given date. -
Django Rest Framework: Upload file to another server via Django
I am building an API with DRF. The purpose of this API is to take user input and post the input to a different server via that servers API. There is also an option for users to upload file e.g. image. But the problem I am facing is that the second server is receiving the file as a blob of text like ����\x00\x10JFIF\x00\x01\x01\x01\x01,\x01,\x00\x00��\x0cXICC_PROFILE\x00\x01\x01\x00\x00\x0cHLino\x02\x10\x00\x00mntrRGB XYZ \x07�\x00\x02\x00\t\x00\x06\x001\x00\x... The second server is also build with Django. Here is the code for the first server that user has direct interaction with: requests.patch( f"https://second-server.com/api/user-upload/{self.kwargs.get('user_id')}/", data=request.data, ) The request.data contains the form data including the file that user is uploading. How can I save image to second server through the first server that user has direct interation with. -
Unable to find locate folder in python directory. Getting the error: ModuleNotFoundError: No module named 'config'
I am trying to import a .py file in my project using relative paths but I'm having some issues. This is my project structure: django_misinfo -config --init.py --definitions.py -scripts --scraper.py This is my definitions.py: import os ROOT_DIR = os.path.realpath(os.path.join(os.path.dirname(__file__), '..')) and this is my scraper.py: import os from config.definitions import ROOT_DIR However, I get an error: ModuleNotFoundError: No module named 'config'. I'm not sure what could be causing this, I've tried everything I can think of, including moving the structure of the folders around. It seems like a simple solution but I'm not sure what I'm doing wrong. Thank you for your help. -
Robots.txt returns 404 instead of displaying text
Problem When trying to request my robots.txt file at website.com/robots.txt, I always receive a 404 error. Files config > urls.py from django.conf import settings from django.contrib import admin from django.urls import path, include, re_path from django.views.generic import TemplateView from django.conf.urls.static import static from config import views from django.conf.urls import handler404, handler500, handler403, handler400 handler404 = views.handler404 handler500 = views.handler500 urlpatterns = [ path('admin/', admin.site.urls), path('accounts/', include('allauth.urls')), path('accounts/', include('django.contrib.auth.urls')), path('', include('pages.urls')), path('plants/', include('plants.urls')), path('robots.txt',TemplateView.as_view(template_name='robots.txt', content_type='text/plain')), ] config > views.py from django.http import JsonResponse, Http404, HttpResponse from django.shortcuts import render def handler404(request, exception=None): return render(request, '404.html', status=404) def handler500(request): return render(request, '500.html', status=500) templates > robots.txt User-Agent: * Disallow: /admin/ Disallow: /accounts/ Parts of my folder structure that may be helpful to know project | |---config | | | |---urls.py | |---views.py | |---templates | |---pages | |---about.html | |---contact.html | |---404.html |---robots.txt I've also tried using only exception instead of exception=None inside of my handler404. I've tried to move the robots.txt views and urls into my pages app with the robots.txt within the pages template folder. I've tried removing the content_type=text/plain from the url pattern. I've read through several different tutorials and I'm not sure what I'm doing wrong. -
Django: managing permissions, groups and users during data migrations
Problem During a data migration, I'm trying to create a django.contrib.auth.models.Group and some Users and then attaching said group to one of the users. Problem I'm finding (other than the permissions still not being created, but I've already found a solution to that), is that for some reason the many-to-many manager doesn't seem to be working as it should (?). Basically what I'm trying to do is something like: group = Group.objects.create(name="manager") # user creation... user.groups.add(group) However, I get the following error: TypeError: Group instance expected, got <Group: manager> Whenever I try to replicate this in the Django shell, it works no problem. It only fails when in a migration. Any ideas? Things I've tried and other information I've tried both populating the m2m relation through the User related manager and the Group related manager, that is, user.groups.add(group) and group.user_set.add(user). Both give me a similar error. Just partially related, but just so I have the permissions needed, I have this first in my migration: for app_config in apps.get_app_configs(): app_config.models_module = True create_permissions(app_config, verbosity=0) app_config.models_module = None The group is supposedly created properly. Given that I create the groups and the users in different helper functions, I actually grab the group … -
How to handle FileNotFound error when using img tag using mark_safe in django admin
I am importing images into AWS S3 using django-storages. However, if Django admin does not have the corresponding image in S3, Admin would like to issue a FileNotFoundError to correct the S3BotoStorage object or fix the underlying problem to handle the error. admin/hospital.py class HospitalAdmin(OrderedInlineModelAdminMixin, IdFieldIncludedModelAdmin): list_display = ("name", "tags_comma_separated", "created_at") list_display_links = ("name",) list_filter = [TagFilter] fieldsets = ( (None, {"fields": ("user",)}), ( None, { "fields": ( "logo_image", "logo_image_width", "logo_image_height", "logo_image_preview", "name", "description", "address", "longitude", "latitude", "near_station_name", "phone_number", "sms_phone_number", ) }, ), ( None, { "fields": ( "created_at", "updated_at", ) }, ), ) readonly_fields = [ "logo_image_width", "logo_image_height", "logo_image_preview", "created_at", "updated_at", ] ... # FileNotFound Error occurs in the lower part @display(description="preview log image") def logo_image_preview(self, obj): return mark_safe( '<img src="{url}" width="{width}" height="{height}" />'.format( url=obj.logo_image.url, width=obj.logo_image.width, height=obj.logo_image.height, ) ) I added a try/except statement to the error part to generate a correct error, but it doesn't seem to solve the fundamental problem try: return mark_safe( '<img src="{url}" width="{width}" height="{height}" />'.format( url=obj.logo_image.url, width=obj.logo_image.width, height=obj.logo_image.height, ) ) except FileNotFoundError as e: return str(e) -
Django NoReverseMatch Error while testing: 'testapp' is not a registered namespace
Hii i try to test my url easily with TestCase and reverse, but i get NoReverseMatch error. urls.py from django.urls import path from . import views app_name = "testapp" urlpatterns = [ path("", views.index, name="index"), ] tests.py from django.test import TestCase from django.urls import reverse class BasicTests(TestCase): def test_index(self): response = self.client.get( reverse('testapp:index')) self.assertEqual(response.status_code, 200) self.assertContains(response, "Hello World") And the error: ERROR: test_index (mysite.tests.BasicTests) ---------------------------------------------------------------------- Traceback (most recent call last): File "django\myvenv\lib\site-packages\django\urls\base.py", line 71, in reverse extra, resolver = resolver.namespace_dict[ns] KeyError: 'testapp' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "django\mysite\mysite\tests.py", line 7, in test_index reverse('testapp:index')) File "django\myvenv\lib\site-packages\django\urls\base.py", line 82, in reverse raise NoReverseMatch("%s is not a registered namespace" % key) django.urls.exceptions.NoReverseMatch: 'testapp' is not a registered namespace What am I missing here? -
Django PasswordResetView does not work for inactive users
I have a simple django app where users can create and login to their accounts. When a user is registering for a new account, the user object is created and saved in the database with the is_active flag set to false. Once the user clicks the confirmation email, the user object has its is_active flag set to true. I have built out a password reset flow using Django's views: PasswordResetView, PasswordResetDoneView, PasswordResetConfirmView, and PasswordResetCompleteView. Everything works as expected unless I am trying to reset the password for an account which has not yet been activated (is_active == False), in which case, the reset password email is never sent to the user. The edge case I am considering here is for a user who created an account, and never clicked the registration link which expires after 72 hours, and thus have a user account which exists but is not active. Then the user wants to get a new registration link, and to do so I require a user to enter their username and password (so that no malicious actors can spam a random users email inbox with new registration link emails). If the user has since forgotten their password, they are … -
Displaying Countdown in Django Loop not working properly when clicked
Hi I have the following Countdown in Javascript, which is inside a Django for loop and it is showing more than once. In my current situation when I click on any of the countdown start button only the first one works. I want to be able to click on any of them and each on of them work separetly when clicked not simultaneously. here is the Script: <button id="myBtn" onclick="myFunction()" type="button" class="btn btn-warning"> <i class="fa-solid fa-play" style="margin-right:2px"></i> <span id="demo" class="countdown-live" style="text-align:center;"></span> </button> <script type="text/javascript"> var countDownDate = new Date(Date.now() + 45000).getTime(); var x = setInterval(function() { var now = new Date().getTime(); var distance = countDownDate - now; var days = Math.floor(distance / (1000 * 60 * 60 * 24)); var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)); var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60)); var seconds = Math.floor((distance % (1000 * 60)) / 1000); document.getElementById("demo").innerHTML = minutes + " : " + seconds + " "; if (distance < 0) { clearInterval(x); document.getElementById("demo").innerHTML = 'Done'; } }, 1000); </script> My question: How to click on any of the countdown buttons inside the django …