Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django is not fetching another app static file but fetching the main app static file?
Django is fetching the main app static files but it is not fetching the other app static files how to solve it ?? Error in CC is: Main File : Html Link Of CC : Main html link : Folder structure : -
Django Rest Framework authentication with Custom User Model
I have multiple types of user in my django app: Employee and Patient. They have fields that are specific to each of them. They are implemented using the AbstractBaseUser model as below: from django.db import models from django.contrib.auth.models import AbstractBaseUser class User(AbstractBaseUser): username = models.CharField(max_length=40, unique=True) USERNAME_FIELD = 'identifier' first_name = models.CharField( max_length=50, null=False, blank=False) last_name = models.CharField( max_length=50, null=False, blank=False) date_of_birth = models.DateField(null=False, blank=False) USER_TYPE_CHOICES = ( (1, 'Patient'), (2, 'Employee'), ) user_type = models.PositiveSmallIntegerField( choices=USER_TYPE_CHOICES, default=1, blank=False, null=False) class Role(models.Model): RoleName = models.CharField(max_length=50, null=False, blank=False) class Employee(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, primary_key=True) employment_start_date = models.DateField(null=False, blank=True) employment_end_date = models.DateField(null=False, blank=True) role = models.ForeignKey( Role, on_delete=models.CASCADE, related_name='assigned_employees') class Patient(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, primary_key=True) I have a few questions with how to go forward with this: How does just the choice in the User class limit the fields that a user has access to? If I had a HTML page would I create an Employee then a User would be created, or the other way round? When I'm using Django Rest Framework, how can I implement a sign up and log in with the two different types? I'm struggling to understand how this would work conceptually. Is … -
Integrating chainable animation image gallery code into Django project
I'm building a website using Django and I want to add this image gallery to one of my pages, but I'm having issues integrating the code. The HTML, CSS, and JS code I want to add is here: https://gist.github.com/CodeMyUI/9769b75c7a81d24138ae74bdbadc39e4 I've added the JS (inside a <script> element) and HTML to my django template, and added the CSS to my project's style.css file, but when I try to render, I'm getting a console error: Uncaught TypeError: Cannot read properties of null (reading 'classList') I also don't see anywhere in the code snippets that points to the images that I want to use for the gallery. Help on what I'm missing to successfully integrate this cool image gallery would be appreciated. -
Migrating sqlite to mysql using Django
I’m new to Django and web servers, and have been stuck for a few days. I inherited a Django app, python version 2.7 and Django version 1.9. The app was previously using the default SQLite databases. I want to migrate to Mysql for performance reasons. I loaded the data into the sqlite db using reset_db I installed mysqlclient I created a mysql db I created a username and password for a user and granted all permissions I dumped the data into a file called dump.json using python manage.py dumpdata > dump.json I changed the settings file to use django.db.backends.mysql I tried to load data using python manage.py loaddata and with makemigrations, migrate, it fails with the following error (with ANY manage.py command): (eKichabiTest) ananditharaghunath@Anandithas-MacBook-Pro db-test % python manage.py migrate Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/opt/anaconda3/envs/eKichabiTest/lib/python2.7/site-packages/django/core/management/__init__.py", line 353, in execute_from_command_line utility.execute() File "/opt/anaconda3/envs/eKichabiTest/lib/python2.7/site-packages/django/core/management/__init__.py", line 345, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/opt/anaconda3/envs/eKichabiTest/lib/python2.7/site-packages/django/core/management/base.py", line 348, in run_from_argv self.execute(*args, **cmd_options) File "/opt/anaconda3/envs/eKichabiTest/lib/python2.7/site-packages/django/core/management/base.py", line 398, in execute self.check() File "/opt/anaconda3/envs/eKichabiTest/lib/python2.7/site-packages/django/core/management/base.py", line 426, in check include_deployment_checks=include_deployment_checks, File "/opt/anaconda3/envs/eKichabiTest/lib/python2.7/site-packages/django/core/checks/registry.py", line 75, in run_checks new_errors = check(app_configs=app_configs) File "/opt/anaconda3/envs/eKichabiTest/lib/python2.7/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/opt/anaconda3/envs/eKichabiTest/lib/python2.7/site-packages/django/core/checks/urls.py", line 23, in check_resolver … -
Order of operations in Django Templates
I'm trying to call a dictionary named test with a key 'example' corresponding to a value 'OK'. I am trying to call it inside of a Django template, i.e. {{test.example}}. The problem is that I want to call this dynamically, so I pass an object and it has an ID of 'example' -> {{test.(object.id)}}. How do I go about this? -
Command Cancelled! on running orator migrate command in django
When I'm running the orator migrate command then giving Command Cancelled! I have installed orator in Django Orator: 0.9 Python: 3.9.7 django: 4.0.5 I create created a migration and model that you can see my code and set the connection but when I'm running migrate command then comming Command Cancelled! db connection orator.py from orator import DatabaseManager import environ env = environ.Env() environ.Env.read_env() config = { 'mysql': { 'driver': 'mysql', 'host': 'localhost', 'database': env('DB_DATABASE'), 'user': env('DB_USERNAME'), 'password': env('DB_PASSWORD'), 'prefix': '' } } db = DatabaseManager(config) migration file from orator.migrations import Migration class CreateProductsable(Migration): def up(self): """ Run the migrations. """ with self.schema.create('products') as table: table.increments('id') table.integer('category_id').unsigned() table.timestamps() table.foreign('category_id').references('id').on('jobs').on_delete('cascade') def down(self): """ Revert the migrations. """ self.schema.drop('products') model file from orator import Model class Product(Model): __table__ = 'products' -
What is this format? (similar to JSON)
I'm getting info from an API (Google Ads API) that looks like this on the browser: customer { resource_name: "customers/XXX" id: XXX } campaign { resource_name: "customers/XXX/campaigns/XXX" status: ENABLED name: "XXX" id: XXX } metrics { impressions: 0 } The source code looks like this: customer { resource_name: "customers/XXX" id: XXX } campaign { resource_name: "customers/XXX/campaigns/XXX" status: ENABLED name: "XXX" id: XXX } metrics { impressions: 0 } I guess this is similar to JSON, but not exactly. Is it a know-format or just random code? I want to turn this data into an HTML table (using Python/Django) and I'm not sure if I can use JSON solutions/libraries (or similar ones) or if I need to create my own custom solution. Thanks! -
Transform VB6 Applications to dual-platform using python
This is my first time asking here, just to be clear I don't want any code or anyone to make something for me, I'm searching for a solution, so I can start building what I want. I searched a lot but didn't find the answer. In our company we have an OLD "Legacy" VB6 application, and if we have a new employee we need to install and do multiple things to make this application work. I found a program called "Thinfinity" that take the application and sorta make it work like a web application and you can access it through an IP address. What I'm searching for here, Is there a way to make the same concept using Python? Again, I don't want someone to make it for me, I just want someone to put me in the right/correct direction to do it Excuse my English & Thanks in Advance -
How to integrate google celender using django rest api
I am unable to integrate Google calendar using Django rest API. I need to use the OAuth2 mechanism to get users' calendar access. -
How to correctly raise the desired error or override the error in the class?
In my code for validating a token, for any error or invalid token, I always gives an error 500. I need to get an error 401, or 403. Here is part of the code. class AzureVerifyTokenError(Exception): pass class InvalidAuthorizationToken(AzureVerifyTokenError): def __init__(self, details=''): super().__init__(f'Invalid authorization token: {details}') def verify_jwt(*, token, valid_audiences, jwks_uri, issuer, verify=True): public_key = get_public_key(token=token, jwks_uri=jwks_uri) try: decoded = jwt.decode( token, public_key, verify=verify, algorithms=['RS256'], audience=valid_audiences, issuer=issuer, ) except jwt.exceptions.PyJWTError as exc: raise InvalidAuthorizationToken(exc.__class__.__name__) else: return decoded What I already tried: In the part where there is a try, I tried to return 401. from rest_framework import status from rest_framework.response import Response ..... except jwt.exceptions.PyJWTError: return Response(status=status.HTTP_401_UNAUTHORIZED) ..... But this obviously doesn't work. Or I don’t import what I need, or I don’t use what I need. Am I doing something wrong, or am I missing something. I even think it should be easy, but I'm completely lost. Perhaps the class AzureVerifyTokenError(Exception): pass is empty for a reason and I can set error there, but how? Any hints and examples will help me. Thank you. -
Django redirect to another view not working, url redirect is though
I have a view that I just want to redirect to another view for test purposes. When I hardcode the URL it works. def testDirect(request): return HttpResponse("redirected to correct pagge") def randomQuestion(request): random_question = Question.objects.order_by('?')[0] return redirect("/polls/testDirect") However, what I really want to do is call it by it's view name. When I look at the docs it gives me this example below: By passing the name of a view and optionally some positional or keyword arguments; the URL will be reverse resolved using the reverse() method: def my_view(request): ... return redirect('some-view-name', foo='bar') But when I try it like that I get the following error def randomQuestion(request): random_question = Question.objects.order_by('?')[0] return redirect('testDirect') Not sure what I am doing wrong -
Django socketio client connects but returns 404 not found
here is my django server.py file import socketio import eventlet SOCKET_PORT = 8000 sio = socketio.Server() app = socketio.WSGIApp(sio) @sio.event def connect(sid, environ): print(sid, 'connected') @sio.event def disconnect(sid): print(sid, 'disconnected') @sio.event def test(sid, data): print(data) def initSocket(request): eventlet.wsgi.server(eventlet.listen(('', SOCKET_PORT)), app) and this is my client.py file import socketio client = socketio.Client() client.connect('http://localhost:8000') client.emit('test', 'hello world') this is wsgi.py file from django.core.wsgi import get_wsgi_application import os import eventlet import eventlet.wsgi os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'b2b_backend.settings') application = get_wsgi_application() eventlet.wsgi.server(eventlet.listen(('', 8000)), application) and finally urls.py file from webSocket.views import initSocket urlpatterns = [ path('', initSocket) ] this is the output of the server when I launch the client.py file from cmd. Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. (22588) wsgi starting up on http://0.0.0.0:8000 (22588) accepted ('127.0.0.1', 58933) Not Found: /socket.io/ 127.0.0.1 - - [29/Jun/2022 19:00:08] "GET /socket.io/ transport=polling&EIO=4&t=1656518406.600064 HTTP/1.1" 404 3092 0.010074 when the django server starts at port 8000, it will also start the socketio server on the same port by calling the initSocket method, then I start the client.py file from cmd (I'm using cmd for testing), all it should do is connect to the server and emit an event. All I'm trying to do is get the clients … -
Django - tests not discovered after moving code to another directory
When my app layout was project/ ├── app1/ │ ├── __init__.py │ ├── tests.py ├── app2/ ├── Dockerfile ... └── manage.py running python manage.py test worked just fine. Then code was moved to src/ dir, i.e. project/ ├── src │ ├── app1/ │ │ ├── __init__.py │ │ ├── tests.py │ ├── app2/ │ ... │ └── manage.py ├── Dockerfile ... and now no tests are discovered root@650001aeb6b5:/app# python src/manage.py test Found 0 test(s). System check identified no issues (0 silenced). ---------------------------------------------------------------------- Ran 0 tests in 0.000s OK I have tried using the -t option but that didn't help root@650001aeb6b5:/app# python src/manage.py test -t src ... ImportError: Start directory is not importable: '/app' Any idea how to make this work? My guess is test discovery configuration should be updated but I have no idea how to do that. -
Django Ajax posting duplicate values to the view
Im trying to post the value of a html item(the id of the item) to the view so it can add the item to the cart, however it always posts the value of the last item printed by the django {% for %} even though the html source says the values are different here is my html <div class="container"> <div class="row row-cols-2 row-cols-md-3" data-masonry='{"percentPosition": true }'> {% for product in products %} <div class="col mb-4"> <div class="card h-100"> {% if product.image %} <img src="{{ product.image.url }}" class="card-img-top" alt="{{ product.description }}"> {% endif %} <div class="card-body"> <h5 class="card-title">{{ product.name }}</h5> <p class="card-text">{{ product.description|slice:":100" }}...</p> <p class="card-text">${{ product.price }}</p> <p> <a class="btn btn-dark gap-2 mb-1" href="{{ product.get_absolute_url }}">View Item</a> <button class="btn btn-outline-success" id="add-to-cart" value="{{ product.id }}">Add to Cart</button> </p> {% if product.in_stock == False %} <p> Item is currently out of stock </p> {% endif %} </div> </div> </div> {% endfor %} </div> </div> Here is the Ajax $(document).on('click', '#add-to-cart', function(e) { e.preventDefault(); $.ajax({ type: 'POST', url: '{% url "add_to_cart" %}', data: { productid: $('#add-to-cart').val(), csrfmiddlewaretoken: '{{ csrf_token }}', action: 'post' }, success: function(json){ }, error: function(xhr, errmsg, err) { } }); }) Here is my view def CartAddView(request): cart = Cart(request) … -
Django validate ModelInlines in Parent Model
Suppose we have 2 django models: class File: # Comma separated list of column names unique_columns = models.CharField(max_length=200) class Column: file = models.ForeignKey(File, on_delete=models.CASCADE) name = models.CharField(max_length=50) In admin.py class ColumnInline(nested_admin.NestedTabularInline): model = Column class FileAdmin(admin.ModelAdmin): inlines = [ColumnInLine] What I want to achieve When saving these models in the Admin page I want to validate whether the Files' unique_columns are also set as Columns related to this File (by validating a related object with that name exists) What I tried Obviously, a clean() method on File won't work as it's saved before Column. Overriding save_formset on FileAdmin, however I don't fully understand how to access the Column forms Question How to achieve this? Is it possible by using a custom form? Or can I override save_formset and do the validation I want? As a more general question: What is a good way to do such validations where validating one form depends on forms of other objects? -
Nested function working but returning messages in Django
I have a function called inside another one. The functions are working properly but, while using a validator to raise some error in case of wrong entries by the users, the validator works but is calling either the success and the error message. I post some code for better explanation. utils.py def add_flight_function(request): try: aircraft_maintenance_type = AircraftMaintenanceType.objects.first() except: aircraft_maintenance_type = None aircraft = request.POST.get('aircraft') adep = request.POST.get('adep') ades = request.POST.get('ades') date = request.POST.get('date') atd = request.POST.get('atd') ata = request.POST.get('ata') function_type_obj = request.POST.get('function_type') function_type_obj = FunctionType.objects.get(id=function_type_obj) operational_condition = request.POST.get('operational_condition') student = request.POST.get('student') instructor = request.POST.get('instructor') night = request.POST.get('night') note = request.POST.get('note') aircraft_type = Aircraft.objects.get( id=aircraft).aircraft_type.abbreviation if aircraft_maintenance_type.is_tacho == True: atd_tacho = request.POST.get('atd_tacho') ata_tacho = request.POST.get('ata_tacho') if float(ata_tacho) <= float(atd_tacho): messages.error( request, "ATA Tacho cannot be lower than ATD Tacho") return HttpResponseRedirect(request.META.get('HTTP_REFERER')) is_valid_flight, error_message = flight_validator( request, ata, atd, function_type_obj.name, instructor) if not is_valid_flight: messages.error(request, error_message) return HttpResponseRedirect(request.META.get('HTTP_REFERER')) else: is_valid_flight, error_message = flight_validator( request, ata, atd, function_type_obj.name, instructor) if not is_valid_flight: messages.error(request, error_message) return HttpResponseRedirect(request.META.get('HTTP_REFERER')) log_entry = LogEntry.objects.create(aircraft_id=aircraft, adep_id=adep, ades_id=ades, date=date, atd=atd, ata=ata, function_type_id=function_type_obj.id, student_id=student, instructor_id=instructor, operational_condition_id=operational_condition, note=note) if night == 'on': log_entry.night_flight = True # if function_type_obj.name == 'Dual Command': # instructor_flight_payment = InstructorFlightPayment(log_entry=log_entry, instructor_id=instructor) # instructor_flight_payment.save() if function_type_obj.name == 'Single … -
Div spacing issue
I would like the lines to be much closer to each other, but margin and height are not working <h4>TITLE:</h4> <div style="width: 290px; display: table-cell;"> <h4>AAA</h4> </div> <div style="display: table-cell;"> <h4>€ 123</h4> </div> <br> <div style="width: 290px; display: table-cell;"> <h4>BBB</h4> </div> <div style="display: table-cell;"> <h4>€ 123</h4> </div> Result: There is almost a full line size between AAA and BBB. That's the issue. -
Are there "N + 1 problems" in "formfield_for_foreignkey()"? (Django)
I overrided formfield_for_foreignkey() to display the combination text of foreign key and its parent to Django Admin as shown below: @admin.register(MyModel) class MyModelAdmin(admin.ModelAdmin): def formfield_for_foreignkey(self, db_field, request, **kwargs): formfield = super().formfield_for_foreignkey(db_field, request, **kwargs) if db_field.name == "my_field": formfield.label_from_instance = lambda obj: f'{obj} ({obj.my_parent})' return formfield Then, with "print()", I checked how many time "formfield_for_foreignkey()" and "if block" in "formfield_for_foreignkey()" are called as shown below: @admin.register(MyModel) class MyModelAdmin(admin.ModelAdmin): def formfield_for_foreignkey(self, db_field, request, **kwargs): formfield = super().formfield_for_foreignkey(db_field, request, **kwargs) print("formfield_for_foreignkey") # Called "18 times" if db_field.name == "my_field": print("if block") # Called "9 times" formfield.label_from_instance = lambda obj: f'{obj} ({obj.my_parent})' return formfield As a result, print("formfield_for_foreignkey") is called 18 times which means "formfield_for_foreignkey()" is called 18 times. And print("if block") is called 9 times which means "if block" in "formfield_for_foreignkey()" is called 9 times. My questions: Is it "N + 1 problem" that: "formfield_for_foreignkey()" itself is called 18 times? "if block" itself is called 9 times? "{obj}" in "if block" is called 9 times? "{obj.my_parent}" in "if block" is called 9 times? -
pass parameters to an modal django?
I'm starting to program with python and django. I'm trying to implement the modal in my web page. I have already achieved the implementation of modals for the creation of objects, but I have a problem updating or deleting, since they require sending a parameter. total_alumnos.html <div class="table-responsive"> <h5>Alumos de Secundaria</h5> <form method="get" class="forms-sample"> <label for="as" >Apellido Paterno:&nbsp;</label>{{filtro.form.apellido_p}} <button class="btn btn-info" type="submit"><i class="fa-solid fa-magnifying-glass"></i>&nbsp; Buscar</button> </form> <br> <table style="text-align:center;" class="table table-bordered table-striped table-contextual "> <tr class="table-info"> <th>Usuario</th> <th>Nombre</th> <th>Apellidos</th> <th>Correo</th> <th>Grado</th> <th>Año</th> <th>Salon</th> <th>Asignar</th> </tr> {% for alumno in alumno %} <tr> <td class="py-1"> <img src="{{alumno.profile_pic.url}}" alt="image" /> </td> <td>{{alumno.nombre }}</td> <td>{{alumno.apellido_p }} {{ alumno.apellido_m }}</td> <td>{{alumno.email }}</td> <td>{{alumno.aula.grado }}</td> <td>{{alumno.aula.año }}</td> <td>{{alumno.aula.salon }}</td> <td><a class="btn btn-sm btn-info btn-rounded" href="{% url 'asignar_alumno' alumno.id %}" ><i class="fa-solid fa-circle-plus"></i>&nbsp;Asignar</a></td> <td><button type="button" data-bs-toggle="modal" data-bs-target="#asignarModal" class="btn btn-info" ><i class="fa-solid fa-circle-plus"></i>Asignar</button></i></td> </tr> {% endfor %} </table> asignar_alumno.html <div class="modal fade" id="asignarModal" tabindex="-1" role="dialog" aria-labelledby="asignarModal" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title">Agregar Curso</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <form method='POST'action="" enctype="multipart/form-data" > {% csrf_token %} <div class="modal-body"> {{aula_form.aula}} </div> <div class="modal-footer"> <a class="btn btn-warning" href="{% url 'total_alumnos' %}">Cancelar</a> <input class="btn btn-primary" type="submit" name="Submit" value="Asignar Aula"> </div> </form> </div> </div> … -
Create a history record in Django for every UPDATE of a class instance
I have a model in Django that is used to create an item of stock class Item(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) description = models.ForeignKey(Item, on_delete=models.CASCADE, related_name='item') amount = models.IntegerField(default=0, blank=False) place = models.ForeignKey(Place, on_delete=models.CASCADE, related_name='place') issue_amount = models.IntegerField(default=0, blank=True) receive_amount = models.IntegerField(default=0, blank=True) The item amount will be updated everytime an item is issued by adding or subtracting the issue or receive amount in a views function that alters the instance amount and calls save on that instance. I want to be able to keep a record of every update and make this information available to both my frontend and to an admin model. I found this tutorial in which the poster creates a separate model with the same field values as Item and then writes SQL commands directly to the database to create a TRIGGER that saves each Item field on every update: https://www.youtube.com/watch?v=d26DUXynf8s Is there a way I can replicate this same behaviour using Django? -
Django query_set order_by default field if ordering field is an empty string
I have a query_set that I want to order by Lower('title'). However, for some elements, title is blank (blank=True). So, when I sort, those elements are rightfully are on top. However, all elements, no matter what, have a default_title. So, I want to use an element's default_title in the sorting if title is blank. -
how to connect my project with zoho books via api in Django
I was trying to integrate my Django project ZohoBooks via API. So I got stuck while generating the AuthToken or Code. how to create an invoice on Zoho books automatically, when the Order objects are created in my Django project. please help!!!! thanks in advance -
Django Celery Redis
I have this error A rediss:// URL must have parameter ssl_cert_reqs and this must be set to CERT_REQUIRED, CERT_OPTIONAL, or CERT_NONE settings CELERY_BROKER_URL = os.environ.get('REDIS_URL', "redis://localhost:6379") CELERY_RESULT_BACKEND = os.environ.get('REDIS_URL', "redis://localhost:6379") CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' celery.py from __future__ import absolute_import, unicode_literals from celery import Celery import os, ssl os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproj.settings') app = Celery( 'myproj', broker_use_ssl = { 'ssl_cert_reqs': ssl.CERT_NONE }) app.config_from_object('django.conf:settings', namespace="CELERY") app.autodiscover_tasks() I changed the value of ssl_cert_reqs to different value 'none', 'cert_required', ..., but nothing, always the same error when I use rediss:// instead of redis://. -
How do I access exception traceback during graphene-django request?
I'm using graphene-django v2.15.0 because that's the latest stable release, which pulls in graphene v2.1.9. Any time an exception is raised during a graphql request, all I get to see is the HTTP response body which looks something like: {"errors":[{"message":"this is my exception","locations":[{"line":1,"column":3}],"path":["hello"]}],"data":{"hello":null}} Just the message, not the traceback, and some useless location information that has nothing to do with the cause. I've spent an hour googling things like "graphene-django errors traceback", and I found tons of results - but all of them were people trying to silence errors and tracebacks, not access them! Am I in the wrong timeline? Did I get Mandela'd? What the hell is going on? BTW - I already tried the following based on a suggestion I found, but it had zero effect on behavior, either in the response or in the console where I have ./manage.py runserver going. import logging ; logging.getLogger("graphql.execution.utils").setLevel(logging.DEBUG) I've also tried looking through graphene and graphene-django docs for settings to flip with no success. -
Get data from second api call based on data coming from the first api (python/django)
I am making a simple web application in pycharm (python/django) that displays data that it picks up from growstuff.org. The main page displays all the crops based on what it finds on growstuff.org/crops.json like the plant's name,scientific name and description. However, info of the plants themselves (like spread,height,days to harvest,sun requirements) are contained in growstuf.org/crops/ID.json. I have already managed to get the data from crops.json and display it on the website,however i can't combine the two files to display the full info i need. How can I make the second call based on the first one's data? views.py apidata = requests.get('https://www.growstuff.org/crops').json() #cropdata = requests.get(f"https://www.growstuff.org/crops/{}.json").json() return render(request, 'index.html', {'apidata':apidata}) index.html <table Width="70%" Height="180px"> <thead> <tr style="font-family:asul; "> <td>Crop</td> <td>Name</td> <td>Scientific Name</td> <td>Description</td> <td>Suniness</td> <td>Companions</td> </tr> </thead> <tbody id="myTable"> {% for i in apidata %} <tr> <td><img src="{{i.thumbnail_url}}" style=" border: 1px solid #ddd; border-radius: 4px; padding: 5px; width: 150px;"></td> <td><h4>{{i.name}}</h4></td> <td><h4>{{i.scientific_name}}</h4></td> <td><h4>"{{i.description}}"</h4></td> {% for j in cropdata %} <td><h4>{{i.j.sun_requirements}}</h4></td> <td><h4>{{i.j.relationships}}</h4></td> {% endfor %} </tr> {% endfor %} </tbody> </table>