Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do you connect Django to an existing Microsoft SQL Server DB stored on Azure?
I have setup a Django API connected to a React frontend. I'm attempting to connect the Django API to an already existing mssql database on Azure. I've installed pyodbc, djagno-pyodbc-azure, and mssql-django. In my settings.py I have the data: DATABASES = { 'default': { 'ENGINE': 'mssql', 'NAME': 'DBNAME', 'USER': 'USERNAME', 'PASSWORD': 'PW', 'HOST' : 'tcp:dbname.database.windows.net', 'PORT': '1442', 'OPTIONS': { 'driver': 'ODBC Driver 13 for SQL Server', } }, } I've tried removing "tcp:" from host, I've tried "sql_server.pyodbc" as the ENGINE. I installed a few different other packages. Whenever I run "python manage.py inspectdb > models.py" to import the models of the existing database I either get an empty models.py file or an error "django.db.utils.Error: ('01000'...". Feel a bit stuck and was wondering if anyone had some guidance. -
Connect Django Postgres to AWS RDS over SSL
I'm digging into Django and thought it would be a nice exercise to connect to an AWS RDS database over SSL, but I can't quite figure out how to provide the SSL-cert from AWS to the database config. I've downloaded the global-bundle.pem from https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/UsingWithRDS.SSL.html. Now in the Django source code, it seems you can pass these parameters to DATABASES: DATABASES = { 'default': { ... 'OPTIONS': { 'sslmode': 'verify-ca', 'sslrootcert': 'root.crt', 'sslcert': 'client.crt', 'sslkey': 'client.key', }, } } My question is, how do I convert/pass the certificate from AWS? -
Django project - database table in cache
I have a Django(python) project running on a digitalocean.com droplet. Because the configurations options are limited I have an excess of free memory. I'm thinking about using that available memory, and load some database tables in memory. I already have a Redis server caching some views. Is it possible to cache a database whole table? How? Thanks. -
How to change gmail contact name in Django emails
I am trying to change my gmail contact name that is sent from Django. Currently, when I send an email, it shows david as the sender when it is from david@mycompany.com. I have tried the other suggestions on SO by setting it up like this: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = os.environ.get('EMAIL_HOST_USER') EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_HOST_PASSWORD') DEFAULT_FROM_EMAIL = f"David at Company <{os.environ.get('EMAIL_HOST_USER')}>" print(DEFAULT_FROM_EMAIL) This results in the error: celery_1 | smtplib.SMTPAuthenticationError: (535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8 https://support.google.com/mail/?p=BadCredentials d8sm7252296pfu.141 - gsmtp') The setting which send the email but have the user as david looks like: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = os.environ.get('EMAIL_HOST_USER') EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_HOST_PASSWORD') I have also tried not using env vars and hard coding it as such: EMAIL_HOST_USER = "David at Company <david@company.com>" to no avail. Thoughts? -
Why my django m2m_changed signal not triggered?
I am trying to validate an image field which have a m2m relationship with the post model by using the m2m_changed signal but it is not being triggered at all. clearly there is something that I am missing but don't know what. class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) images = models.ManyToManyField('Files', blank=True) here is my signals.py file from django.dispatch import receiver from django.db.models.signals import m2m_changed from django.core.exceptions import ValidationError @receiver(m2m_changed, sender=Post.images.through) def images_changed(sender, **kwargs): print("the images signal changed ran") And I also defined the ready method in my apps.py file. def ready(self): import social.signals -
Form validation django
I am a beginner,I got this assignment in which I have to create django app. But am not able to understand how to do that ,so below are the requirements of the app. The app should have to form and each form should have proper JavaScript validation. The inputs in the first form say (gender of the applicant) should determine the field shown on the second form. I didn't understood the 2 nd point , do i have to create log in /sign up or what -
Ordering by computed field in admin panel
I'm learning Django and I got stuck on this problem I'm basically trying to order by a computed field in an admin panel view, I've read some "tutorials" like this: https://books.agiliq.com/projects/django-admin-cookbook/en/latest/sorting_calculated_fields.html on google but I can't seem to figure out how it all works (between annotations etc) Here's my classes: class StockAdmin(admin.ModelAdmin): list_display = ("ticker_symbol", "security_name", "current_pretax_yield", "current_aftertax_yield", "displayed_price") search_fields = ("ticker_symbol", "security_name") def current_pretax_yield(self, obj): try: curyield = float(obj.coupon_amount/obj.last_price) return str(round((curyield*100),3)) + "%" except: return "n/a" def current_aftertax_yield(self, obj): try: withholding_tax = 15 at_yield = ((obj.coupon_amount/obj.last_price*100)*(1-(withholding_tax/100))*0.74) return str(round(at_yield, 2)) + "%" except: return "n/a" def get_queryset(self, request): queryset = super().get_queryset(request) queryset = queryset.annotate( _current_aftertax_yield=self.current_aftertax_yield(), _current_pretax_yield=self.current_pretax_yield(), ) current_aftertax_yield.admin_order_field = '_current_aftertax_yield' current_pretax_yield.admin_order_field = '_current_pretax_yield' Basically, I want to get "coupon amount" and "last price" fields from the database, perform the calculations you see in the functions, then display those calculated files in the admin panel and be able to "order by" them The code as I have now errors out with a TypeError: current_aftertax_yield() missing 1 required positional argument: 'obj' I've tried to follow this: https://books.agiliq.com/projects/django-admin-cookbook/en/latest/sorting_calculated_fields.html but I can't quite figure it out on my own.. Any ideas? Is there an easier way of doing this? I used a lot of … -
Authenticate several apps with same Oauth2 provider using one callback url
I currently have a chrome extension which authorizes with an Oauth2 provider and then authenticates with my django rest framework backend using allauth. I want to add two new apps to the same backend; a iOS app and an Android app. They shall both use the same Oauth2 provider. Currently the Oauth provider has stopped the possibility to add new apps, which means I only have the possibility of ONE callback url, which is currently used by the Chrome extension. Is there a way of designing the auth flow to send redirect and callback to the backend for all three (using just one callback url), and somehow be able to send my backends api token back to the apps? -
Uncaught TypeError: Cannot read properties of undefined (reading 'childNode')
hi I am trying to follow the below tutorial for my formset only i find problem in part: container.insertBefore (newForm, addButton) and the error that presents me is the following: calculos.js: 195 Uncaught TypeError: Cannot read properties of undefined (reading 'childNode') I've already tried everything but can't find the childNode JS let parteForm = document.querySelectorAll(".part-form") let container = document.querySelector("#part-form-container") let addButton = document.querySelector("#add-form") let totalForms = document.querySelector("#id_form-TOTAL_FORMS") let formNum = parteForm.length-1 // Get the number of the last form on the page with zero-based indexing addButton.addEventListener('click', addForm) function addForm(){ //e.preventDefault() let newForm = parteForm[0].cloneNode(true) let formRegex = RegExp(`form-(\\d){1}-`,'g') formNum++ newForm.innerHTML = newForm.innerHTML.replace(formRegex, `form-${formNum}-`) container.insertBefore(newForm, addButton) //parentnode.insertbefore(newnode,elnodoantesdelcualseinsertanewnode) //#part-form-container.insertbefore(div.part-form,) totalForms.setAttribute('value', `${formNum+1}`) } HTML <form method="POST" id="part-form-container"> {% csrf_token %} <div class="row"> <div class="col-12"> <div class="card"> <div class="card-body"> <div class="row mb-3"> <div class="col-md-12"> <div class="mb-3"> <label for="verticalnav-email-input">Summary</label> {{presupuestosparteform.resumen}} </div> </div> </div> <h4 class="card-title">Parts list</h4> <p class="card-title-desc">Add the parts that you need to include.</p> <input type="button" class="btn btn-block btn-default btn-success mb-4" id="add-form" onclick="addForm()" value="+ Add part" /> <div class="table-responsive"> <table class="table table-bordered table-nowrap align-middle" id="childTable1"> <tbody> {{ formset.management_form }} {% for form in formset %} <div class="part-form"> <tr> <td> {{form.codigo}} </td> <td> {{form.descripcion}} </td> </tr> </div> {% endfor %} </tbody> </table> </form> -
xxxx matching query does not exist
I am trying to query data from a csv file to django, this is the code of the query : from django.core.management.base import BaseCommand import pandas as pd from website.models import Product class Command(BaseCommand): help='import booms' def add_arguments(self, parser): pass def handle(self,*args,**options): df=pd.read_excel('tt.xlsx',engine='openpyxl') for P_N,P_P in zip(df.Product_name,df.Price): models=Product.objects.get(Product_Name=P_N,Product_Price=P_P) models.save() here this the code of my models.py : from django.db import models # Create your models here. class Product(models.Model): Product_Name=models.TextField() Product_Price=models.TextField() #Product_Link=models.TextField() def __str__(self): return self.name knowing that my csv file is the following : http://prntscr.com/26cjw4a the error that I'm getting is this "Product matching query does not exist " http://prntscr.com/26cjw9n -
Google Cloud Run: Cant connect to Postgress SQL
I am following this tutorial to upload my existing Django project running locally on sqlite to Google Cloud Run / Postgres. I have the cloud_sql_proxy service running and can sign into Postgres from the command line. I am at the point of running the command python manage.py migrate And I get the error: django.db.utils.OperationalError: connection to server on socket "/cloudsql/cgps-registration-2:us-central-1:cgps-reg-2-postgre-sql/.s.PGSQL.5432" failed: No such file or directory Is the server running locally and accepting connections on that socket? The answer to that questions is Yes, the server is running locally and accepting connections because I can log in with the Postgres client: agerson@agersons-iMac ~ % psql "sslmode=disable dbname=postgres user=postgres hostaddr=127.0.0.1" Password for user postgres: psql (14.1, server 13.4) Type "help" for help. postgres=> I double checked the connection string in my .env file and it has the correct UN / P Is this scoket not getting created somehow in a previous step? /cloudsql/cgps-registration-2:us-central-1:cgps-reg-2-postgre-sql/.s.PGSQL.5432 -
¿How to iterate through model images in production?
finally i deployed my first blog in heroku, but im stucked at serving each post image since in my local code whas iterating with image.url from the model. Now i have whitenoise configured but i dont know how to get the static image that is specific to each post from the model. This is my code actually: model: class BlogPost(models.Model): class BlogPostObjects(models.Manager): def get_queryset(self): return super().get_queryset().filter(status='publicado') options = ( ('borrador', 'Borrador'), ('publicado', 'Publicado') ) categoria = models.ForeignKey(BlogCategoria, on_delete=models.PROTECT,default=1) titulo = models.CharField(max_length=250) excerpt = models.TextField(null=True,max_length=200) contenido = RichTextField() slug = models.SlugField(max_length=250, unique_for_date='publicado',null=False, unique=True) publicado = models.DateTimeField(default=timezone.now) autor = models.ForeignKey(Usuario,on_delete=models.CASCADE,related_name="autor") status = models.CharField(max_length=10,choices=options,default='borrador') imagen = models.ImageField(default= "empty.jpg" ,null=True, blank = True) likes = models.ManyToManyField(Usuario, related_name="blog_post") objects = models.Manager() postobjects = BlogPostObjects() view: class BlogInicio(ListView): template_name = "Blog/blog_inicio.html" model = BlogPost context_object_name = "posts" paginate_by = 6 template: {% for post in posts %} <div class="col-md-4" > <div class="card-content"> <div class="card-img"> {% if post.imagen %} <img src="{{post.imagen.url}}"/> {% else %} <img src="https://archive.org/download/placeholder-image/placeholder-image.jpg" /> {% endif %} <span><h4>{{post.autor}}</h4></span> <span style= "margin-top:43%;"><h4>{{post.categoria}}</h4></span> </div> <div class="card-desc"> <h3>{{post.titulo}}</h3> <p>{{post.excerpt|truncatechars:50}}</p> <a href="{% url 'blog:post_detalle' post.pk %}" class="btn-card">Leer</a> </div> </div> </div> {% endfor %} i know in line 6 from the template i could do a <img src="{% static … -
DJANGO How to know if an object pk is in my request.path
I need to compare an url with if condition in Django html template, to make an options menu selected when I'm on this page. I have this but doesn't works well: {% for vehiculo in vehiculos %} {% if "/calendar/vehicle/{{ vehiculo.pk }}/" in request.path %} <a class="list-group-item list-group-item-action active"> {% else %} <a class="list-group-item list-group-item-action"> {% endif %} {% endfor %} In my url I have this. But doesn't works!!! I don't find any solutions in Django docs or here in stackoverflow, github... Any solution is worth, thanks! -
Django Rest Framework Return on User's Resources in Nested Serializer
I am trying to return just the user's resources in a nested serializer response. My current response looks like this: { "id": 5174, "resourceName": "name here", "moreInformation": [ { "id": 15924, "infoName": "stuff here", "infoDetails": [ { "id": 51, "createdBy": 1, "detail": "detail here", "moreInformation": 15924 }, { "id": 52, "createdBy": 3, "detail": "detail here", "moreInformation": 15924 } ] } ] } I'm trying to make it to where when the user GETs the ResourceName endpoint, that the infoDetails only shows the infoDetails that were createdBy that user. The current response returns all of the infoDetails regardless of the createdBy field. I'm able to only return the infoDetail if the current user's id matches the createdBy id on the ListInfoDetails view, but not on the DetailResourceName view. Is there a way to do this on the serializer, or is it best to do it in the view? Views: class ListInfoDetail(generics.ListCreateAPIView): queryset = InfoDetail.objects.all() serializer_class = InfoDetailSerializer def get_queryset(self): user = self.request.user return user.infodetail_set.all() class DetailResourceName(generics.RetrieveAPIView): queryset = ResourceName.objects.all() serializer_class = ResourceNameDetailSerializer Serializers: class InfoDetailSerializer(serializers.ModelSerializer): class Meta: model = InfoDetail fields = ['id', 'created_by', 'mnemonic_picture', 'block'] class MoreInformationSerializer(serializers.ModelSerializer): info_details = InfoDetailSerializer(source="infodetail_set", many=True, read_only=True) class Meta: model = MoreInformation fields = ['id', … -
ValueError at /index.............The QuerySet value for an exact lookup must be limited to one result using slicing
I'm building a socialmedia website in django.While I tried to list all the comments in the index page, i am getting this error, The QuerySet value for an exact lookup must be limited to one result using slicing. what should i do in this case views.py.... def index(request): if request.user.is_authenticated: allPost = Post.objects.all().order_by('-created_on').filter(creater = request.user) allBlog = Blogpost.objects.all() comments = PostComment.objects.filter(post=allPost) context = {'allPost' : allPost, 'allBlog' : allBlog, 'comments' : comments} return render(request, 'index.html', context) else: return render(request, "signoption.html") models.py.... class PostComment(models.Model): sno = models.AutoField(primary_key=True) comment = models.TextField() user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True) created_on = models.DateTimeField(default=timezone.now) def __str__(self): return str(self.sno) + '.....comment By.....' + str(self.user) index.html.... {% for comment in comments %} <div class="comment"> <div class="comment-user"> <div class="comment-usr-dp"> <img src="{%static 'img/profile/profile.png'%}" alt=""> </div> </div> <div class="comments-usr-usrname"> <b><h1>{{comment.user.username}}</h1></b> </div> <div class="comment-text"> <h1>{{comment.comment}}</h1> </div> <div class="comment-time"> <h1>{{comment.created_on}}</h1> </div> </div> {%endfor%} -
'QuerySet' object has no attribute 'date_start'. Django rest framework
I am new to Django. In my project I want to filter all the room with available status, then I want start_date to be updated to the current datetime. But I am getting the following error: 'QuerySet' object has no attribute 'start_date' I have the following class in the models.py: class RoomStatus(models.Model): room = models.ForeignKey(Room, on_delete=models.DO_NOTHING) class RoomStatusChoices(models.IntegerChoices): AVAILABLE = 1 UNAVAILABLE = 2 room_status = models.SmallIntegerField(choices=RoomStatusChoices.choices, default=RoomStatusChoices.AVAILABLE) start_date = models.DateTimeField(auto_now=True) In serializers.py I wrote an update with this code available_rooms = RoomStatus.objects.filter(room=room, room_status=RoomStatusChoices.AVAILABLE) print(available_rooms) available_rooms.start_date = max(available_rooms.start_date, datetime.now()) The result of print(available_rooms) is <QuerySet []> Can someone help me? thanks indvance. -
how to grab a data from existing field in Django
I have a web page that I have to connect with Django. So I have an existing form with input and submit button. I have created a model and form. I put {{form}} tag and a little unstyled form appeared. but I want to grab a data from the one in HTML file. The code: form file: class NumberForm(ModelForm): class Meta: model = Number fields = "__all__" HTML: <form action="#" method="post"> {% csrf_token %} {{ form }} <div class="line <input type="text" class="form-control" name="phoneNumber" id="phoneNumber2" value="" placeholder="+7 (___) ___-__-__"> <button class="button_blue">t</button> </div> <label class="container_checkbox"> <input type="checkbox" checked="checked"> <span class="checkmark"></span> </label> </form> -
User.username as foreign key in table - django
My models.py file is having this model with required packages class Userdetails(models.Model): user_id=models.IntegerField(primary_key=True) user_name=models.ForeignKey(User, null=True,on_delete=models.CASCADE)``` I am using User model of Django, I want to store username field of User model to the user_name. When i am trying to access Users.user_name, its giving some integer value instead of username. How to get the username copied to user_name I tried with db_column and to_field but both are showing errors. version iam using is django 4.0 -
reverse for url (*) with keyword arguments not found
I am a django rest/django noob. I am trying to reverse url @action(detail=True, methods=['post'], url_path='request-reset-email', url_name='request-reset-email') def request_reset_password_email(self, request, pk): ... uid64 = urlsafe_base64_encode(smart_bytes(user.id)) token = PasswordResetTokenGenerator().make_token(user) relativeLink = reverse('user-password-reset-confirm', kwargs={'uid64' : uid64, 'token': token}) and I have this other custom action @action(detail=False, methods=['get'], url_path='password-reset/<uid64>/<token>/', url_name='password-reset-confirm') def password_reset_confirm(self, request, uid64, token): pass and this is the urls file router = DefaultRouter() router.register('user', UserViewset, basename='user') urlpatterns = [ path('', include(router.urls)), path('<int:id>', include(router.urls)), ] the error NoReverseMatch at /user/2/request-reset-email/ Reverse for 'user-password-reset-confirm' with keyword arguments '{'uid64': 'Mg', 'token': 'az3s71-eae533db00d974ba7d7fc0dfd5e9e060'}' not found. 4 pattern(s) tried: ['(?P<id>[0-9]+)user/password-reset/<uid64>/<token>\\.(?P<format>[a-z0-9]+)/?$', '(?P<id>[0-9]+)user/password-reset/<uid64>/<token>//$', 'user/password-reset/<uid64>/<token>\\.(?P<format>[a-z0-9]+)/?$', 'user/password-reset/<uid64>/<token>//$'] -
Is there a way to seperate progammatic access to a Django Rest API from React access and what are the alternatives?
This is obviously a design question, and probably me overthinking. I was asked once how to generate API Keys and I explained the process of retrieving tokens( DjangoRest -> React) to which I was responded with "Thats for logging in/authentication, how would you implement 'Generate API key'". If my application is DjangoREST + React, this means my entire application is exposed as RESTful. Is there even a way to control the "frontend" access over being programmatically accessible, since "CLI/Scripting" users can just hit the login endpoint programmatically anyway? It seems like the only thing that can be done here with a React Front and DjangoREST backend is to limit the calls to each of the routes, but control "browser-based" requests vs cli-based requests are nearly impossible. (Unless I blacklist/whitelist by user agent but that seems highly unfeasble) What I am concluding is that the only way to "control" programmatic access effectively in Django is not to use a React Frontend, and then create separate URLs for the api. But then in this case, I am confused on the neccesity of client_IDs and client_secrets (as I have seen on other sites that offer an API), because if I simply blacklist a … -
In Django how to process the file inside request.FILES?
for file in request.FILES: print("") video_input_path = file img_output_path = 'output.jpg' subprocess.call(['ffmpeg', '-i', video_input_path, '-ss', '00:00:00.000', '-vframes', '1', img_output_path]) print("") I'm trying to generate a thumbnail for the File (Video) uploaded via Form, this is pure python solution for generating the thumbnail from any video (works for pictures too but there is a better solution with PIL) video_input_path = file How do I access the file itself here? As far as I know my only options are file = request.FILES['filename'] file.name # Gives name file.content_type # Gives Content type text/html etc file.size # Gives file's size in byte file.read() # Reads file -
How to render and navigate django based web pages with a click of button without refreshing the page (Ajax)
am doing a django project and I would like my navigation bar to be AJAX based in the sense that when I click the link of a particular page, the page is rendered without reloading/refreshing the original page. I have tried to use the django redirect function but without success. your help will be appreciated. -
Android Retrofit upload images and text in the same request
I have an Android app that has a form feature where I collect data, that data contains image answers and text answers and each answer has a question id that I need to send also to know which question to save answer to it in the backend API, I tried to send all answers both images and text in the same request using Retrofit but got some errors, so I thought in another solution, but it's not working anymore here is my code Here is my solution and I need to improve it Retrofit code to send a request with data @Multipart @POST(SUBMIT_FORM) suspend fun submitFormAPI( @Header("Authorization") token: String, @Part("questions_answers") questions_answers: List<QuestionAnswer>, @Part answer_image: MultipartBody.Part?, @Part("question_id") question_id: String?, ): Response<FormResponse> and here is the QuestionAnswer Model, I tried to put answer_image inside it but doesn't work data class QuestionAnswer( val question_id: String, val answer_value: String? = null, ) so in this function, after collecting the data I need to loop through questionImagesAnswers and send a request with the image and its question_id every iteration along with other answers in questionAnswers fun onFormSubmit() { val questionAnswers = mutableListOf<QuestionAnswer>() val questionImagesAnswers = mutableListOf<QuestionModel>() questionImagesAnswers.forEach { questionImagesAnswer -> formViewModel.submitFormAPI( token = token, questionAnswers … -
Avoid Booking past dates with django
I have created an appointment booking system however i want to avoid any past dates being booked before it reaches create booking object which is then saved to the database. Here is my views.py class BookingView(View): def get(self, request, *args, **kwargs): return render(request, "availability.html") def post(self, request, *args, **kwargs): form = AvailabilityForm(request.POST) if form.is_valid(): data = form. cleaned_data bookingList = Appointment.objects.filter(start__lt=data['end_time'], end__gt=data['start_time']) if not bookingList: booking = Appointment.objects.create( name=data["name"], email=data["email"], start=data["start_time"], end=data["end_time"] ) booking.save() name_user = data["name"] start_time = data["start_time"] end_time = data["end_time"] email_user = data["email"] send_mail("Virtual PT Session", f"Thanks {name_user} For Booking Your Appointment with us.\n" + f"Please join the following zoom link on {start_time} \n" + " https://us04web.zoom.us/j/8339571591?pwd=dG9MQy9nUWN6a0F2dUo4L04rQkxPQT09", "engage.fitness.training.1@gmail.com", [email_user], fail_silently=True) return render(request, "success.html", { "booking":booking },) else: name = data["name"] return render(request, "booked.html",{ "name":name, },) -
I am developing an blockchain project using Django and can I know how to resolve this error
Traceback (most recent call last): File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\USER\Desktop\blockchain\wallet\views.py", line 17, in index live_bitcoin_price = live_price[1].getText() Exception Type: IndexError at / Exception Value: list index out of range #code of that function def index(request): if request.method == 'POST': addr = request.POST['addr'] res2 = requests.get('https://cryptowat.ch/') soup2 = bs4.BeautifulSoup(res2.text, 'lxml') live_price = soup2.find_all('span', {'class': 'price'}) live_bitcoin_price = live_price[1].getText() live_bitcoin_price1 = live_price[1].getText() res = requests.get('https://www.blockchain.com/btc/address/'+addr) if res: soup = bs4.BeautifulSoup(res.text, 'lxml') # bal = soup.find_all('span', {'class': 'sc-1ryi78w-0 bFGdFC sc-16b9dsl-1 iIOvXh u3ufsr-0 gXDEBk'}) bal = soup.find_all('span', {'class': 'sc-1ryi78w-0 gCzMgE sc-16b9dsl-1 kUAhZx u3ufsr-0 fGQJzg'}) bal[4].getText() final_bal = bal[4].getText() final_bal1 = final_bal.replace(" ", "").rstrip()[:-3].upper() transactions = bal[1].getText() total_received = bal[2].getText() total_received1 = total_received.replace(" ", "").rstrip()[:-3].upper() total_sent = bal[3].getText() total_sent1 = total_sent.replace(" ", "").rstrip()[:-3].upper() final_bal1_int = float(final_bal1) total_received1_int = float(total_received1) total_sent1_int = float(total_sent1) live_bitcoin_price1_int = float(live_bitcoin_price1) balance_usd = final_bal1_int*live_bitcoin_price1_int total_received_usd = total_received1_int*live_bitcoin_price1_int total_sent_usd = total_sent1_int*live_bitcoin_price1_int else: return redirect('/')