Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
NoReverseMatch in Django Password Reset
I'm using Django 3.1 and I'm trying to reset the password. Every step goes fine but one: After the password reset using PasswordResetConfirmView, I use success_url to reach the PasswordCompleteView, but a NoReverseMatch Error is raised: http://127.0.0.1:8000/customer/reset/Mjg/set-password/reset/done/ : Mjg/set-password/ always stay in the middle. How can I remove this ? Thank so much for your help -
Vscode: Don't have access to .venv python interpreter when venv is created in a subfolder
There's an issue puzzling me, so this is the scenario: I create a clean folder and start VSCode in it. I create a subfolder (say 'server') and cd into it (VSC integrated terminal). I initialise a virtual environment and install my dependencies (I use Pipenv) so my tree so far looks like this: . └── server ├── .venv └── Pipfile I can see in my zsh prompt that indeed the virtual environment is active However, I cannot find the interpreter for my virtual environment in the list of available ones: (Note that Python 3.9.1 64-bit ('server':pipenv) is missing from the options) As a result, if I create for example a django app, I get warnings all over the place about imports not being resolved. If I instead start VSCode directly in the server directory, I have no issues and I can select it: But this is not what I need, as I need to have access to both my backend and frontend in the same VSCode project. Please note that I want to have my .venv folder inside server and not in the root of the project. What's the point I'm missing and why am I unable to use/choose my … -
Django Queryset Filter Performance Optimization
I'm seeing high database CPU utilization based on the following code in my Django app: existing_host = Host.objects.filter(names__contains=[hostname]).first() I have around 300,000 hosts in my database which isn't a huge amount so I'm wondering how I can optimize the performance of this query. RDS Performance Insights SQL SELECT "hosts_host"."id", "hosts_host"."created", "hosts_host"."last_updated", "hosts_host"."names", "hosts_host"."domain_id", "hosts_host"."os_id", "hosts_host"."certificate_id" FROM "hosts_host" WHERE "hosts_host"."names" @> ARRAY[?]::varchar(?)[] ORDER BY "hosts_host"."names" ASC LIMIT ? models.py class Host(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) created = models.DateTimeField(auto_now_add=True) last_updated = models.DateTimeField(auto_now=True) names = ArrayField(models.CharField(unique=True, max_length=settings.MAX_CHAR_COUNT), default=list, null=False) ip_addresses = models.ManyToManyField(IPAddress) services = models.ManyToManyField(Service) domain = models.ForeignKey(Domain, on_delete=models.CASCADE) os = models.ForeignKey(OperatingSystem, on_delete=models.CASCADE, blank=True, null=True) ciphers = models.ManyToManyField(Cipher, blank=True) certificate = models.ForeignKey(Certificate, on_delete=models.CASCADE, blank=True, null=True) class Meta: ordering = ['names'] def __str__(self): return "[Host object: id = {}, names = {}, domain = {}]".format(self.id, self.names, self.domain) def __repr__(self): return "[Host object: id = {}, names = {}, domain = {}]".format(self.id, self.names, self.domain) def __eq__(self, other): if isinstance(other, Host): return sorted(self.names) == sorted(other.names) return False def __hash__(self) -> int: return hash(tuple(sorted(self.names))) def __lt__(self, other): return self.names[0] < other.names[0] def get_absolute_url(self): return '/explore/{}/{}'.format(self.domain.name, self.id) -
Enable submit if one of checkbox is checked in each group
I found some threads on stack but they are pretty old and kinda not suitable for me. So I have two checkbox groups and in them im generating 2 or 3 checkboxes via django, how can I enable my submit when at least one checkbox is checked in each group. this is what i found that was similar to mine problem but it don't work with backend generated checkboxes function check(element) { var cb1 = document.getElementById("checkbox1"); var cb2 = document.getElementById("checkbox2"); var sub = document.getElementById("submit"); if (cb1.checked == true && cb2.checked == true) sub.disabled = false; else sub.disabled = true; } This is how im generating my checkboxes <div class="xTypeDiv"> {% for x in xType %} <input type="checkbox" value="{{ x.type }}" name="pType" class="pChecbkox" id='checkbox1' onclick="check();"> {% endfor %} </div> <div class="yTypeDiv"> {% for x in yType %} <input type="checkbox" value="{{ x.type }}" name="pType" class="pChecbkox" id='checkbox2' onclick="check();"> {% endfor %} </div> -
In Django, how to fix a fetch() function that returns Cors header Access-Control-Allow-Origin error since adding subdomains to NGINX?
I'm using Django and use a JS fetch() function in my html to load a local json file. It looks like this: fetch("{% static 'mylocal.json' %}",{method:"GET", headers:{'Content-Type': 'application/json'}}) .then(...) This function used to work just fine until I recently added subdomains wildcard to NGINX (done through certbot letsencrypt). When I run the html, the fetch() function above now returns an error message that says: Access to fetch at 'https://example.com/static/mypathto/mylocal.json' from origin 'https://mysubdomain.example.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. I've followed detailed tutorials to add the corsheaders package to Django and set all the parameters like these ones : CORS_ORIGIN_ALLOW = True CORS_ALLOWED_ORIGINS = [ 'mysubdomain.example.com', 'www.example.com', 'example.com', ] CORS_ORIGIN_WHITELIST = [ 'mysubdomain.example.com', 'www.example.com', 'example.com', ] But all this corsheaders and corsheaders-middleware in Django did not fix it. So I assume this is down to a configuration I've got to add to my NGINX server blocks ... but I'm not really sure. I've done the following with it but it did not fix it : My /etc/nginx/sites-enabled/example.com file looks like this: server … -
Django - excluding objects from queryset results in "expression tree is too large"
I'm working on a project that handles astronomical data (literally and figuratively) and have hit a roadblock when trying to exclude observations that require complex filtering. To be more specific, each Observation has one or more SpectralWindows. Users must be able to query observations by - among others - looking to their frequency coverage in relation to a band, a frequency range or an emission line. Regardless of the selected option, this coverage can be redshifted inside a specific z interval. Since it's a bit hard to directly translate this to __lte-like selectors, I just filter the queryset and manually exclude observations that don't cover the calculated frequency range. Something like this: for o in obs_result: covers = covers_ranges(z_bands, o) # <--- a more complex filtering solution if(not covers): obs_result = obs_result.exclude(id=o.id) # <--- here's the problem! # update the min and max frequency values across the obs set else: min_max = get_min_max_f(o) min_freq = min(min_freq, min_max[0]) max_freq = max(max_freq, min_max[1]) The resulting query ends up like this: SELECT ... FROM "common_observation" WHERE ("common_observation"."dec" >= 1.3365999999999998 AND "common_observation"."dec" <= 3.3366 AND "common_observation"."field_of_view" <= 300.0 AND "common_observation"."ra" >= 149.2375 AND "common_observation"."ra" <= 151.2375 AND NOT ("common_observation"."id" = 415) AND NOT ("common_observation"."id" … -
How to compare variable with list content that are passed from view to template django
I'm new to Django and trying to solve a simple problem. I looked through many similar questions but still is not able to find the solution. In my template I have a few checkboxes which are built according to records in the database. My Model is: class Status(models.Model): statusCode=models.IntegerField() definition = models.CharField(max_length=30) def __str__(self): return f"{self.definition}" In my view I'm getting the values of checkboxes that user chose and store them in the list: if request.method == "POST": status_list = request.POST.getlist('statuses') I pass this list as a context: return render(request, 'search/index.html',{"chosen_statuses": status_list, "statuses": Status.objects.all()} Then I want to display results of the query keeping the checkboxes that user selected - selected. This is my code in template: <div> <label for="status">Include statuses: </label> {% for status in statuses %} <input type='checkbox' value='{{ status.id }}' name='statuses' {% if status.id in chosen_statuses %} checked {% endif %}> <label for='{{ status }}'>{{ status }}</label> {% endfor %} </div> The list "chosen_values" contains the user's choices as needed, and the results of the query are correct. But the checkboxes are left unchecked. I would appreciate some help. -
Where does Django store session data?
I want to create my own web framework in Go. I want the framework to resemble django. I'm currently in the brainstorming phase, and I was wondering where Django stores the session data? Does it store it in memory? Perhaps in a JSON file? Or does it use a database such as Redis or MySQL? -
Django+Nginx page loads buffering text output and very slow
The page will load very slow but all that is being returned is a large amount of text. The text is in a table and the table loads row by row. It's so slow that each cell of the table can be seen loading individually. This is not happening on my local development machine. However, on two identical Ubunutu virtual machine servers, it's occurring. The issue occurs in both Chrome and Firefox. The page load may be seen here: http://128.31.25.32/spectra/ docker-compose.yaml: version: '3' services: db: container_name: postgresdb image: postgres:latest restart: always env_file: - project.env ports: - 5432:5432 volumes: - postgres-data1:/var/lib/postgresql/data1 plumber: build: ./rplumber/ command: /app/plumber.R restart: always env_file: - project.env ports: - 7002:8000 volumes: - ./rplumber:/app web: container_name: django build: maldidb/ command: > gunicorn soMedia.wsgi:application --bind 0.0.0.0:8000 --workers=4 --timeout 1000 env_file: - project.env expose: - 8000 depends_on: - db - plumber volumes: - staticfiles:/home/app/web/static/ - /home/ubuntu/r01data:/home/app/r01data/ nginx: container_name: nginx image: nginx:mainline-alpine restart: always ports: - 80:80 volumes: - ./nginx:/etc/nginx/conf.d - staticfiles:/home/app/web/static/ depends_on: - web - db - plumber volumes: postgres-data1: staticfiles: nginx.conf: upstream djangoapp { server django:8000; } server { listen 80; listen [::]:80; location / { proxy_pass http://djangoapp; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location /static/ … -
I have getting wrong values after perrforming some arithmetic in Django views and templates
I am trying to grab some data from the template, perform some arithmetic and display it to the end-users, I noticed that I am getting the wrong answers after manually calculating the result, so I tried to print the values which I have grabbed from my templates on the console and I get the right answer but the final calculation is having some errors in it. I don't know how to grab the "NET_COST", "PROFIT" and "ROI" to the message, that's why I have used a static "$100". I know little how "f strings" and "formats" but I don't know how to apply it here views.py def Profitcalculator(request): if request.method == 'POST': SP = request.POST.get("sp") fees_on_sp = request.POST.get("fees-on-sp") transport = request.POST.get("transport") extra_cost = request.POST.get("extra-cost") product_cost = request.POST.get("product-cost") ADS = request.POST.get("ads") GIVEAWAY = request.POST.get("giveaway") NET_COST = (fees_on_sp + transport + extra_cost + product_cost + ADS + GIVEAWAY) PROFIT = (int(SP) - int(NET_COST)) ROI = (int(PROFIT)/int(NET_COST)) * 100 print(SP, ADS, GIVEAWAY) print(NET_COST, PROFIT, ROI) messages.info(request, "Your NET_COST is $100") return render(request, 'core/profit-calculator.html') console 600 2 7 510425027 -510424427 -99.99988245090498 profit-calculator.html <form method="post"> {% csrf_token %} <div class="row form-group"> <div class="col-md-4"> <input class="m-t-10 au-input au-input--full" type="number" name="sp" placeholder="Selling Price" required> </div> <div class="col-md-4"> … -
Authentication login problem in running two django projects at the same time in same PC machine
I have two different django projects in same a computer and i run both the project by giving command python manage.py runserver 8000 and python manage.py runserver 8001. They both run without any error but when i open them in a same chrome browser in two different tabs and trying to login in both projects they are reset and return to login page again. I am trying to say that when i login in first project it login successfully and then i login in second project it also login successfully but the first project comes to reset and return in login page again. it seems that browser only allows only one login at a time. is there anything about django session either in Cookies session or Authentication Session? and do i have to add or change something in settings.py file? -
How to set cookie in my custom authentication view( django-rest-framework-simplejwt)?
After login access and refresh token seted in httponly cookie.So I create CustomAuthentication(Inherit from JWTAuthentication) view to get the httponly cookie.If access token invalid at that time InvalidToken error except(see my below code) then generate new access token by using refresh token. Question 1 : How to set this access token in cookie?.Here I use Response() but it not work because CustomAuthentication view return user and token instead of response. Question 2 : Any other recommended way to generate new access token by using refresh token and set in cookie? Sorry for my English.. authenticate.py: from rest_framework_simplejwt.authentication import JWTAuthentication from rest_framework_simplejwt.exceptions import InvalidToken from django.conf import settings import requests import json from datetime import timedelta from .utility import set_browser_cookie from rest_framework.response import Response def set_browser_cookie(response,key,value): response.set_cookie( key = key, value = value, # expires = settings.SIMPLE_JWT['ACCESS_TOKEN_LIFETIME'], secure = settings.SIMPLE_JWT['AUTH_COOKIE_SECURE'], httponly = settings.SIMPLE_JWT['AUTH_COOKIE_HTTP_ONLY'], samesite = settings.SIMPLE_JWT['AUTH_COOKIE_SAMESITE'] ) class CustomAuthentication(JWTAuthentication): def authenticate(self, request): header = self.get_header(request) if header is None: raw_token = request.COOKIES.get(settings.SIMPLE_JWT['AUTH_COOKIE_ACCESS']) or None else: raw_token = self.get_raw_token(header) if raw_token is None: return None try: validated_token = self.get_validated_token(raw_token) except InvalidToken: refresh = request.COOKIES.get(settings.SIMPLE_JWT['AUTH_COOKIE_REFRESH']) if refresh is None: return None protocol = 'https' if request.is_secure() else 'http' url = f'{protocol}://127.0.0.1:8000/auth/api/token/refresh/' data = … -
Django {% static %} in javascript file
I have a problem with my script.js and my base.html In my script.js: function switchLogo() { var imgElement = document.getElementById('logo'); if (imgElement.src.match(img1)) { imgElement.src = img2;; imgElement.style.width = "220px"; imgElement.style.height = "30px"; } else { imgElement.src = img1; imgElement.style.width = "40px"; imgElement.style.height = "40px"; } } In my base.html {% load static %} <script> var img1 = "{% static 'base/assets/images/logo.png' %}" var img2 = "{% static 'base/assets/images/logo2.png' %}" </script> <script src="{% static 'base/assets/js/utilities.js' %}"></script> The static path works for others elements like my favicon in my base.html but not when it's my js file, I don't find my mystake, when I run the server, I have the messages Not Found: /assets/images/logo2.png Not Found: /assets/images/logo.png In the GET messages I see for my favicon the static folder (/static/base/assets/images/favicon.ico) but not for the logos (GET /assets/images/logo.png) -
use str() inside {% %} django
i try to compare object to a string within {% %} with str() but not working . cause when i do type(room.status) = class main.models.status {% if 'str(room.status)' == "Vacant" %} <button type="button" class="btn btn-success btn-outline-dark btn-lg"> check in {% elif room.status == 'Occupied'%} <button type="button" class="btn btn-dark btn-lg"> Check out {%elif room.status == 'Reserve'%} <button type="button" class="btn btn-warning btn-outline-dark btn-lg"> Reserve in {%else%} <button type="button" class="btn btn-danger btn-outline-dark btn-lg"> Check status {%endif% -
I have tried many solutions but image is not showing when I run server. ;( on django
{% extends "base.html" %} {% load static %} {% block content %} <h1>{{ project.title }}</h1> <div class="row"> <div class="col-md-8"> **<img class="img-fluid" src="{{project.image}}">** </div> <div class="col-md-4"> <h5>About the project:</h5> <p>{{ project.description }}</p> <br> <h5>Technology used:</h5> <p>{{ project.technology_used }}</p> </div> </div> {% endblock %} I got this error: [20/Feb/2021 21:49:31] "GET /project/1 HTTP/1.1" 200 1427 Not Found: /project/static/img/1-webgrow.jpg and the static folder is in project directory. This is the view function: def details(request, pk): project = Project.objects.get(pk=pk) context = { 'project': project } return render(request, 'details.html', context) please help -
Django: How To Use Custom Path Converter To Pass A List Through URL
I am trying to pass a list from a form to view so that i can filter a queryset by that list. I am trying to do this with a custom path converter, but i have never made one before so can someone show how you would go about making a path converter that takes in a list and passes that into the view. converters.py class ListPathConverter: def to_python(self, value): return value def to_url(self, value): return value -
id parameter in get request
I am new to Django and a small detail has been bothering me.I have an api endpoint that returns the details of one patient. I have made a successful get request and tested on postman. It returns data for a particular patient with id = 996(I have hard coded the id). But I need to set it so it can pick the id from params in postman instead of the hard coded one here. How can I set params and append them on the url so that I use the id fed in postman instead of hard coding? Kindly assist views.py class PatientDetailsView(GenericAPIView): authentication_classes = [TokenAuthentication] permission_classes = [IsAuthenticated] @classmethod @encryption_check def get(self, request, *args, **kwargs): try: result = {} auth = cc_authenticate() res = getPatientDetails(auth["key"], id) result = res return Response(result, status=status.HTTP_200_OK) except Exception as e: error = getattr(e, "message", repr(e)) result["errors"] = error result["status"] = "error" return Response(result, status=status.HTTP_400_BAD_REQUEST) api_service.py def getPatientDetails(auth, id): print("getting patientdetails from Callcenter") try: print(auth) # print(url) id= 996 headers = { "Authorization": f'Token {auth}' } url = f'{CC_URL}/patients/v1/details/?id={id}' print(url) res = requests.get(url, headers=headers) print("returning patientdetails response", res.status_code) return res.json() except ConnectionError as err: print("connection exception occurred") print(err) return err urls.py path("details/", views.PatientDetailsView.as_view(), name="patient_info"), -
Django - Create or Update reverse foreign key object from parents DetailView
I would like to Create or Update a Child object when on the Parent object DetailView. I have two models, as follows: class Parent(models.Model): name = models.CharField(max_length=50) class Child(models.Model): name = models.CharField(max_length=50) parent = models.ForeignKey( 'Parent', related_name='children', on_delete=models.CASCADE) I have the following view: class ParentDetailView(DetailView): model = Parent What would be the best approach to allow the Creating or Updating of a Child object whilst on the ParentDetailView ? I have seen the following approach in Django docs - https://docs.djangoproject.com/en/2.2/topics/class-based-views/mixins/#using-formmixin-with-detailview Many Thanks -
Cannot execute callback for subscribe to a channel event
I'm trying to catch any 'subscription_succeeded' event from JavaScript with Pusher->Channels. var generalChannel = pusher.subscribe('general-channel'); generalChannel.bind('pusher:subscription_succeeded', callback) I can see Pusher->Debug Console that the 'subscription_succeeded' event is fired-up when a subscription is made but the callback is not executed(it's executed only for the current one). If I'm triggering my own event from Javascript them I'm able bind the callback but I'd like the one that Is automatically triggered by Channels. Any suggestions is much appreciated. -
How do i receive image file in django view from fetch post without using django forms
In this project i am using a different flow approach. I am not using the traditional django forms neither the django templates tags. I am using Vanilla javascript fetch for all data manipulation. All my fecth configuration are okay i have added enctype="multipart/form-data" and {% csrf_token %} to my form and this is my html corresponding the issue at hand: <input style="cursor: pointer" type="file" placeholder="Aucun Fichier" id="image_upload" value="Choisir Fichier" name="image_upload" class="img_class" />. My problem now is that i want to upload an image file to my server. For that purpose i have the following code: //My event listener submit_btn.addEventListener("click", (event) => { event.preventDefault(); const user = new Users(); user_image_upload = image_upload.value user_image_file_field = image_file_field.files[0] ... // My object i send to the server post_user_info_object = { obj_user_image_upload: user_image_upload, obj_image_file_field: user_image_file_field, .... } } When i post the form this is my image printed on the javascript console: Next, when it reaches the server this is how it looks like (i'm posting the code first before the image): @login_required def edit_profile(request): if request.user.is_authenticated: if request.method == 'POST' or request.method == 'FILES': data = json.loads(request.body.decode("utf-8")) print("Data: ", data) raw_image_file = data["obj_image_file_field"] print('image file: ', raw_image_file) ... And the following is the image … -
The "Else if" statement in my Django templates appears after the HTML header block
I have some data which I am passing from my views to my templates, whenever the else if the statement is true(that is the if the statement is false) the statement appears after my HTML header(). My main issue is that why is the else block not under the HTML heaader where I have put it in the code templates.html <table class="table table-borderless table-data3"> <thead> <tr> <th>No</th> <th>Email</th> <th>Telephone</th> <th>Country</th> <th>Status</th> <th>Image</th> <th>Actions</th> </tr> </thead> <tbody> {% if supplier %} {% for supplier in suppliers %} <tr> <td>{{forloop.counter}}</td> <td>{{supplier.email}}</td> <td>{{supplier.telephone}}</td> <td>{{supplier.country}}</td> <td class="process">Active</td> <td>{{supplier.image.url}}</td> <td> <div class="table-data-feature"> <button class="item" data-toggle="tooltip" data-placement="top" title="Edit"> <i class="zmdi zmdi-edit"></i> </button> <button class="item" data-toggle="tooltip" data-placement="top" title="Delete"> <i class="zmdi zmdi-delete"></i> </button> </div> </td> </tr> {% endfor %} {% else %} <h2>No supplier available</h2> {% endif %} </tbody> </table> -
Django - How to fetch external API
I need to fetch some fiat conversion rates from an API but I'm not sure how finish my task. Basically I want to be able to convert from every fiat to every fiat. my function: def get_exchange_rates_fiat(): currencies = ['EUR', 'USD', 'GBP', 'CNY', 'HKD', 'INR', 'RUB'] for currency in currencies: api_url = 'https://api.exchangeratesapi.io/latest' parameters = { 'base': currency, } headers = { 'Accepts': 'application/json', } session = Session() session.headers.update(headers) try: response = session.get(api_url, params=parameters) fiat_conversion_rates = response.json()['rates'] for fiat_conversion_rates in fiat_conversion_rates: FiatConversionRates.objects.update_or_create( key=fiat_conversion_rates['slug'], value=currency ) logger.info("Fiat conversion rate for" + ' ' + str(currency) + ' ' + "updated successfully.") except Exception as e: logger.exception("Something went wrong while processing task: 'Update Fiat conversion rates', please investigate") raise Exception(e) models.py class FiatConversionRates(models.Model): base = models.CharField(max_length=3) key = models.CharField(max_length=3) value = models.DecimalField(max_digits=12, decimal_places=2) Seems that I dont understand how to read the API myself, as I dont know how to make the allocation to my database fields :( can smb. help? -
`clean()` doesnt work properly with foriegnkey
I have 2 models Transaction and FamilyGroup and im making some validations like below class Transaction(models.Model): chp_reference = models.CharField(max_length=50, unique=True) rent_effective_date = models.DateField(null=True, blank=True) income_period = models.CharField(max_length=11) property_market_rent = models.DecimalField(max_digits=7) number_of_familygroup = models.DecilmalField(max_digits=10) def clean(self): count_fg = self.family_groups.count() if self.number_of_family_group != count_fg: raise ValidationError( ' Number of family group doesnt match with FG_NO.') class FamilyGroup(models.Model): name = models.CharField(max_length=10) transaction = models.ForeignKey(Transaction, on_delete=models.CASCADE,related_name='family_groups') last_rent = models.DecimalField(max_digits=7) the probelm is when i change number_of_familygroup to eg. 3 and i make 3 FamilyGroup objects, it still give me an error Number of family group doesnt match with FG_NO , it doesnt let me save the new values. What is the best approach to make it work properly? Thanks in advance! -
django cart.js loop is not running
cart.js this is not working nothing is printed in the console or some declaration is wrong answer quickly var updateBtns = document.getElementsByClassName('update-cart') for(var i=0 ; i<updateBtns.length ; i++) { updateBtns[i].addEventListener('click',function(){ var productId = this.dataset.product var action = this.dataset.action console.log(productId,action) }) } is there any mistake in html code {% for product in products %} {% if product.category == "Dosa" %} <div class="product"> <tr> <td><h5>{{ product.name }}</h5></td> <td><h5>{{ product.price }}</h5></td> <td><button data-product={{product.id}} data-action="add" class="btn btn-warning btn-add update-cart">Add to cart</button></td> </tr> </div> {% endif %} {% endfor %} -
How do display JSON in Django template? Block.io API
I am testing the api from block.io https://block.io/api/simple/python { "status" : "success", "data" : { "network" : "BTCTEST", "available_balance" : "0.0", "pending_received_balance" : "0.0", "balances" : [ { "user_id" : 0, "label" : "default", "address" : "2NCjjB8iVKu9jnYpNcYKxxRYP9w6eWXZAq4", "available_balance" : "0.00000000", "pending_received_balance" : "0.00000000" } ] } } I would like to display for example only the wallet address of the user in question so that he can make a deposit. My views.py from django.shortcuts import render from block_io import BlockIo version = 2 # API version block_io = BlockIo('28a8-ba34-8b81-137d', '1111111', version) def index(request): balance = block_io.get_address_balance(labels='shibe1') context = {'balance': balance} return render(request, 'home.html', context) home.html <h1>Block.io API</h1> {{ balance }} <h1>I want display example this data</h1> <h1>Label: default</h1> <h1>Available balance: 0.00000000</h1> <h1>Pending received balance: 0.00000000</h1> <h1>Address: 2NCjjB8iVKu9jnYpNcYKxxRYP9w6eWXZAq4</h1> When I do this all the data is displayed but example I only want to address Image displayed data {'status': 'success', 'data': {'network': 'BTCTEST', 'available_balance': '0.0', 'pending_received_balance': '0.0', 'balances': [{'user_id': 1, 'label': 'shibe1', 'address': '2NADUMWksxJZRKPSNXya8R2LYQY2fGa5mNY', 'available_balance': '0.00000000', 'pending_received_balance': '0.00000000'}]}} How can I refer only to the data that I want?