Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to solve CORS error caused from API Calls made by Chrome extension DOM element inserted to a webpage
Im trying to make an API request to my backend server (Django) from the chrome extension. The API request goes through from the Popup.html and Popup.js but I'm facing the CORS issue when I am trying to make the request via a custom DOM element which I had inserted into Webpage. For example: I want to fetch the list of users. The Api request works fine when I open the chrome extension and make the API request. When I make the same API request after insert a new DOM element from chrome extension into any Webpage. The API is throwing CORS error. As the origin inside request headers get set to the current webpage which is not inside my allowed origin. Is there any way in which we can resolve the CORS issue without adding the LinkedIn website Url to allowed origins. I have tried multiple implementations all of which failed miserably. -
How to filter foreign key choices in admin form based on another field while changing (before saving)
I have a model with two foreign key fields class LabTesting(models.Model): fk_farm = models.ForeignKey("Farm", verbose_name=_("Farm"), on_delete=models.SET_NULL, null=True, blank=True) fk_house = models.ForeignKey("House", verbose_name=_("House"), on_delete=models.SET_NULL, null=True, blank=True) fk_house has a fk_farm foreign key field I want to limit the fk_house choices in admin page to the selected farm but while changing before clicking save I tried to edit the form but I couldn't get it to work dynamically in the change list page without saving the object -
How to render sphinx static files in django view
I have a sphinx documentation and django projet in two separate folder. When I try to render the sphinx template in my django projet, I loose all the css style and js link. Is there a way load all dependencies? -
Django - How to track user progress across multiple days?
I have a django model that updates with the user's current time spent on the website: totallearningtime = models.DecimalField(default = 0, decimal_places=2, max_digits=100) # total time user spent on website And I have the following chart.js that I want to populate with the totallearningtime through the week, and reset at the begining of the next week: (right now it has placeholder values) Here is the code for the chart: <script> const ctx = document.getElementById("myChart"); // <block:setup:1> const DATA_COUNT = 12; const labels = [ "Mon", "Tue", "Wen", "Thur", "Fri", "Sat", "Sun", ]; const datapoints = [ 0, 20, 20, 60, 60, 120, 140, 180, 120, 125, 105, 110, 170, ]; const data = { labels: labels, datasets: [ { label: "Learning Time", data: datapoints, // borderColor: red, fill: false, cubicInterpolationMode: "monotone", tension: 0.4, }, ], }; new Chart(ctx, { type: "line", data: data, options: { responsive: true, maintainAspectRatio: true, plugins: { title: { display: false, text: "Total Time: 5h 45m", }, }, interaction: { intersect: false, }, scales: { x: { display: true, title: { display: true, }, }, y: { display: true, title: { display: true, text: "Hours", }, suggestedMin: 0, suggestedMax: 200, }, }, }, }); </script> However, … -
How to add field to every historical model in django simple history
Tracking which change to a model has been made is easy. But tracking which changes have been conducted together during a single "operation" or "action" is more difficult. I would like to add an additional field to all historical models that stores a key referencing the action during which an object has been changed. In order to add a field to a historical model that is generated by the django-simple-history package one has to add an abstract class for each model and install a model specific signal handler in the apps' config. When working with 50+ models this is quiet a lot of unDRY code. How would I add a field to all historical models? -
Pydantic raises ValidationError not allowing "None" using FastAPI and Django ORM
So I have the following model in my database (Django ORM): # Database Models handled by Django ORM import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "superpower.settings") import django django.setup() from django.db import models class Order(models.Model): """Test Table""" text = models.CharField(max_length=50) amount = models.IntegerField() the following Pydantic schema: from pydantic import BaseModel # Base Class for Model "Order" class OrderBase(BaseModel): text: str amount: int class Config: orm_mode = True this view: from . import models, schemas def create_order(order: schemas.OrderBase): models.Order.objects.get_or_create(text=order.text, amount=order.amount) and finally the following routes: from fastapi import APIRouter, Depends, HTTPException from .. import models, schemas, views router = APIRouter( prefix="/orders", tags=["orders"], responses={404: {"description": "Not found"}}, ) @router.post("/create/", response_model=schemas.OrderBase) def create_orders(order: schemas.OrderBase): return views.create_order(order=order) When I now call http://127.0.0.1:8000/api/orders/create with the body { "text": "test1", "amount": 40 } I get this error: File "/Users/jonas/Desktop/superpower/venv/lib/python3.10/site-packages/uvicorn/protocols/http/h11_impl.py", line 407, in run_asgi result = await app( # type: ignore[func-returns-value] File "/Users/jonas/Desktop/superpower/venv/lib/python3.10/site-packages/uvicorn/middleware/proxy_headers.py", line 78, in __call__ return await self.app(scope, receive, send) File "/Users/jonas/Desktop/superpower/venv/lib/python3.10/site-packages/fastapi/applications.py", line 270, in __call__ await super().__call__(scope, receive, send) File "/Users/jonas/Desktop/superpower/venv/lib/python3.10/site-packages/starlette/applications.py", line 124, in __call__ await self.middleware_stack(scope, receive, send) File "/Users/jonas/Desktop/superpower/venv/lib/python3.10/site-packages/starlette/middleware/errors.py", line 184, in __call__ raise exc File "/Users/jonas/Desktop/superpower/venv/lib/python3.10/site-packages/starlette/middleware/errors.py", line 162, in __call__ await self.app(scope, receive, _send) File "/Users/jonas/Desktop/superpower/venv/lib/python3.10/site-packages/starlette/middleware/exceptions.py", line 79, in __call__ raise exc File "/Users/jonas/Desktop/superpower/venv/lib/python3.10/site-packages/starlette/middleware/exceptions.py", … -
Django Can't See Where I Typed in User ID
So I'm creating a web app in Django, and I encountered this error: my urls.py: from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('<int:user_id>/', views.profile, name="profile"), #path('signup/', views.signup, name="signup"), path("signup/", views.signup, name="signup") ] my views.py: from django.shortcuts import render, get_object_or_404 from django.contrib.auth import forms from django.urls import reverse_lazy from django.http import HttpResponse, Http404 from django.template import loader from .models import User from .forms import SignUpForm from datetime import datetime def index(request): cool_people_list = User.objects.order_by("-username")[:5] _template = loader.get_template("front_page.html") context = { "cool_people_list" : cool_people_list, } return HttpResponse(_template.render(context, request)) def profile(request, user_id): try: user = get_object_or_404(User, pk=user_id) _template = loader.get_template("profile.html") context = { "user" : user } return HttpResponse(_template.render(context, request)) except: raise Http404("The user you are looking for doesn't exist.") def signup(request): if request.method == "POST": form = SignUpForm(request.POST) if form.is_valid(): rn = str(datetime.today().strftime("%Y-%m-%D")) rn2 = str(datetime.today) """usr_list = User.objects.order_by('-join_date') latest_usr = usr_list.first()""" new_user = User(3, str(form.cleaned_data.get("username")), str(form.cleaned_data.get("password")), rn, rn2) new_user.save() return render(request, "signup.html") my models.py: from django.db import models from django.core.validators import MinLengthValidator import datetime class User(models.Model): user_id = models.IntegerField(unique=True) username = models.CharField(max_length=25, validators=[MinLengthValidator(3)]) password = models.CharField(max_length=25, validators=[MinLengthValidator(7)]) join_date = models.DateField() last_online = models.DateTimeField() def __str__(self): return self.username I kept trying different methods, like manually … -
Django how to register model users to admin panel
I am making a site, the idea is that users can post and comment, but i messed up the models(i think) and now i have 2 seperate groups of users. My goal is to combine these 2 groups that they would be able to post and comment. When i login with an admin user and try to post something i can only use the users that i have created from the model(i have a dropdown menu that assigns and existing user to a post) I have: Admin panel users that can't post or comment, but can register, login and log out And: Model created users that can create posts and comment, but i assign them manually to posts/comments Here is my models User code: class User(models.Model): username = models.CharField('Username', max_length=100) description = HTMLField() interests = models.ManyToManyField(Interest, related_name='user_interest') Here is my models Post code: class Post(models.Model): **post_name = models.CharField('Post name', max_length=100)** description = HTMLField() updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) interest_tag = models.ManyToManyField(Interest, related_name='interest_tag') post_host = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) Here is my models Comment code: class Comment(models.Model): **user = models.ForeignKey(User, on_delete=models.CASCADE)** post = models.ForeignKey(Post, on_delete=models.CASCADE) body = models.TextField() updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) I'm pretty green so not sure how … -
how to extract value from FK
I have this org object (org1) which is showing in my page. This is reference to a foreign key in the model. When I do just {{ orgid }} I get the above, I can't figure out how to actually get the value - that Foreign Key = 'org1' Can anyone help please? -
How to fix a bug in Django
When I was working on a Django project (blog), I had an error(s) while working on the site. Here are the errors I have appeared: 1: When I entered the python command manage.py makemigrations blog(via the console) in the directory C:\mysite\site\miniproject , then there is this: Traceback (most recent call last): File "manage.py", line 23, in <module> main() File "manage.py", line 19, in main execute_from_command_line(sys.argv) File "C:\Program Files\Python36\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Program Files\Python36\lib\site-packages\django\core\management\__init__.py", line 395, in execute django.setup() File "C:\Program Files\Python36\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Program Files\Python36\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "C:\Program Files\Python36\lib\site-packages\django\apps\config.py", line 301, in import_models self.models_module = import_module(models_module_name) File "C:\Program Files\Python36\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 978, in _gcd_import File "<frozen importlib._bootstrap>", line 961, in _find_and_load File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 655, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed File "C:\mysite\site\miniproject\blog\models.py", line 5, in <module> class Post(models.Model): File "C:\mysite\site\miniproject\blog\models.py", line 12, in Post author = models.ForeignKey(User, related_name='blog_posts') TypeError: __init__() missing 1 required positional argument: 'on_delete' Although I did everything according to the instructions on the website https://pocoz .gitbooks.io/django-v-primerah/content/sozdanie-i-primenenie-migracij.html. I … -
Django: Heroku Postgres resets uploaded data every idle
My problem seems to be the same as addressed in this page. However, I believe I am using an add-on for my case, specifically the Heroku Postgres. In case it is needed, here is a part of my settings.py: BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = env.str("SECRET_KEY") DEBUG = env.bool("DEBUG", default=False) ALLOWED_HOSTS = \[".herokuapp.com", "localhost", "127.0.0.1"\] CSRF_TRUSTED_ORIGINS = \['https://8000-abcdarl-hivforecastingd-4p274ahpjtp.ws-us67.gitpod.io'\] # Database DATABASES = { 'default': env.dj_db_url("DATABASE_URL") } # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/4.1/howto/static-files/ STATIC_URL = 'static/' STATICFILES_DIRS = \[BASE_DIR / 'static'\] STATIC_ROOT = BASE_DIR / 'staticfiles' STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' # Default primary key field type # https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' Here is a screenshot of my config variables: Screenshot of my config variables In my Django admin, I could still see all my uploaded files, but I could only download the recent ones and it would say not found in the previous ones. This is my first time deploying an application and using Heroku, so I am still new with every process involved. Thank you in advance. I don't know what to try as I am still new with everything, but I kept on researching how to handle it and I couldn't find … -
Django: html input type=input and checkbox
I have a problem with send data from input type='number' to django view. I have a page with products, each of them has a checkbox and a quantity selection (input type='number') <form action="{% url 'create-order' %}" method="POST"> {% csrf_token %} <table class="table table-responsive table-borderless"> <thead> <th>&nbsp;</th> <th>Quantity</th> </thead> <tbody> {% for item in items %} <tr class="align-middle alert border-bottom"> <td> <input type="checkbox" id="check" name="item" value="{{ item.id }}"> </td> <td> <input class="input" min="1" value=1 type="number" name="quantity"> </td> </tr> {% endfor %} </tbody> </table> <div class="submitButton"> <button type="submit" class="lgbtn green">Go to order</button> </div> </form> Submit button go to view: def create_order(request): quantities = request.POST.getlist('quantity') items = request.POST.getlist('item') return JsonResponse({ 'quantities': quantities, 'items': items }) For example, I have 6 products with id = 1, 2, 3, 4, 5, 6. And if I choose 1, 2, 3 and set quantities: 3, 4, 5, then I get: items = [1, 2, 3] # it's OK quantities = [3, 4, 5, 1, 1, 1] # but I need [3, 4, 5] Ideally, I want items and quantities to be in the same object (For example [(1, 3), (2, 4), (3, 5)] or dict {1: 3, 2: 4, 3: 5}), but not necessarily, but in any … -
Modify one to many relationship in Django
I have two models in a one to one relationship: class GPSDevice(models.Model): device_name = models.CharField(max_length=50) class SessionGPS(models.Model): start= models.IntegerField() end= models.IntegerField() gps_device = models.OneToOneField(GPSDevice, on_delete=models.CASCADE, related_name="sesion_gps_device") I realized I have a mistake, a GPSDevice can have many SessionGPS. The problem is that to correct this I should delete the one to one relation in SessionGPS and add a ForeignKey field in GPSDevice: class GPSDevice(models.Model): device_name = models.CharField(max_length=50) session_gps = models.ForeignKey(SessionGPS, on_delete=models.CASCADE, related_name="sesion_gps") #added class SessionGPS(models.Model): foco = models.BooleanField(default=False) inicio_sesion = models.IntegerField() fin_sesion = models.IntegerField() #gps_device = models.OneToOneField(GPSDevice, on_delete=models.CASCADE, related_name="sesion_gps_device") deleted I have already data in the database and I fear that migrating this can produce a mess in the database as have happened before to me. Is there another way, like doing something in the SessionGPS model? -
Flutter Web Sign in with google WITHOUT firebase gives null access token
im trying to implement google sign in with my flutter application which sends the access token to my django back end. I have everything working except, I seem to keep getting null access token. I get the ID token but that I can't send to my back end. is there some problems with trying to get the access token for flutter web (WITHOUT firebase). GoogleSignInAccount? googleaccount = await _googleSignIn.signIn(); final googleauth = await googleaccount.authentication; everything normally works fine for my mobile apps but this is me not using firebase for web. any help would be appreciated. -
How to integrate FastAPI into Django project to use Django's ORM?
I am trying to integrate FastAPI into my Django project which shall serve as an extra app (reason is that I want to use Django's ORM). Now when I run uvicorn wsgi:app --reload it returns ModuleNotFoundError: No module named 'superpower' The only tutorial I found was this which is fairly outdated. Note that I included the FastAPI app electron into the INSTALLED_APPS in my django settings. Running the command uvicorn applications.electorn.wsgi:app --reload from the project root returns ModuleNotFoundError: No module named 'applications' -
A booking form in django that fills a dropdown menu with available times
I am able to display the available times in a dropdown menu, but when I submit the form it wont save to the database. I have two forms, the first the user selects a date and the second is where the available dates should show up in a dropdown menu. models.py Slots = ( ('9.00 - 10.00', '9.00 - 10.00'), ('10.00 - 11.00', '10.00 - 11.00'), ('11.00 - 12.00', '11.00 - 12.00'), ('12.00 - 13.00', '12.00 - 13.00'), ('13.00 - 14.00', '13.00 - 14.00'), ('14.00 - 15.00', '14.00 - 15.00'), ('15.00 - 16.00', '15.00 - 16.00'), ('16.00 - 17.00', '16.00 - 17.00'), ('17.00 - 18.00', '17.00 - 18.00'), ) class Booking(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) slot = models.CharField(max_length=15, choices=Slots) booking_date = models.CharField(max_length=15, default='foo') def __str__(self): return f'{self.user} has booked a PT at {self.slot} on {self.booking_date}' views.py def DateView(request): form = DateForm(request.POST or None) if form.is_valid(): request.session["dateSelected"] = str( form.cleaned_data["booking_date"]) #sends user to next form return redirect('create') context = { 'form': form } return render(request, "bookingapp/date_form.html", context) def BookingView(request): instance = Booking(booking_date=request.session.get( 'dateSelected'), user=request.user) form = BookingForm(request.POST or None, instance=instance) # get all times from bookings on the provided date booked_slots = Booking.objects.filter(booking_date=request.session.get( 'dateSelected')).values_list('slot', flat=True) available_slots = [] for slot in … -
how to redirect to homepage in django-microsoft-auth if there is no next parameter?
I registered the app in Azure AD and configured my Django app so I can log in using a Microsoft account. The problem I am facing is changing the redirect from the admin page to my homepage. Mu redirect URI on Azure looks like this: https://localhost:8000/microsoft/auth-callback/ What do I need to do to change the redirect to https://localhost:8000/home -
Django ListView display items with for loop. Mirror every 2nd
I am working on a django product overview page. I display categories with a listview. I use a Bootstrap grid with two columns to display the categories as follows: picture | Info I now ant every 2nd column to be mirrored so the end resukt will be like this: Picture | Info Info | Picture Picture | Info How do I run a loop to make this work? My code looks like this: <div class='container'> {% for category in categories %} <!-- Check is subcategory exists. if not, filter on category. If it does exist filter on subcategory --> {% if category.sub_category is Null %} <a href="{% url 'academy:brandByCat_list' category.category_name %}"> <div class="row py-3 item-display"> <div class='col-md item-img'> <img src= {{category.category_picture.url}} class="img-fluid category-picture"> </div> <div class="col-md"> <h1 class='py-3'>{{category.category_name}}</h1> <p>{{category.category_info}} </div> </div> </a> {% else %} <a href="{% url 'academy:brandBySubCat_list' category.sub_category %}"> <div class="row py-3 item-display"> <div class='col-md item-img'> <img src= {{category.category_picture.url}} class="img-fluid category-picture"> </div> <div class="col-md"> <h1 class='py-3'>{{category.sub_category}}</h1> <p>{{category.category_info}}</p> </div> </div> </a> {% endif %} {% endfor %} Thanks for the help! -
Django how the link ManytoManyField data with FloatField data?
I have manytomanyfield inside my model.The manytomanyfield field lists the products in the products table. I want to enter the amount for each product I choose. How can I relate manytomanyfield to floatfield field? That's my model: ` class TaskSources(models.Model): id = models.AutoField(primary_key=True) user_task_id = models.ForeignKey(UserTask,on_delete=models.CASCADE) product_id = models.ManyToManyField(Product, verbose_name="Product",default=None) product_amount = models.FloatField(max_length=255,verbose_name="Product Amount") ` The form: ` class TaskSourcesForm(forms.ModelForm): class Meta: model = TaskSources fields = ['product_id', 'product_amount'] ` The views: ` @login_required(login_url="login") def addUserTask(request): user_task_form = UserTaskForm(request.POST or None,initial={'user_id': request.user}) task_sources_form = TaskSourcesForm(request.POST or None) if request.method == 'POST': if user_task_form.is_valid(): user_task = user_task_form.save(commit=False) user_task.author = request.user user_task.save() print(user_task.id) if task_sources_form.is_valid(): task_sources = task_sources_form.save(commit=False) task_sources.user_task_id = UserTask(id = user_task.id) task_sources.save() task_sources_form.save_m2m() messages.success(request,"Task added successfully!") return redirect(".") context = { "user_task_form" : user_task_form, "task_sources_form" : task_sources_form, } return render(request,"user/addtask.html",context) ` Thanks for care. I tried associating the two fields with each other, but I could not succeed. -
View didn't return HTTPResponse object
I was trying to create a blog app by following an online Django tutorial and while I was testing the sign-up page, I ran into a Value Error saying that the view did not return a HTTP response object. i tried everything but i could not find the answer as i am not a Django expert in the users app's views.py file was the code that threw the error from django.shortcuts import render, redirect from django.contrib.auth.forms import UserCreationForm from django.contrib import messages def register(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): username = form.cleaned_data.get('username') messages.success(request, f'Account Created for {username}') return redirect('blog-home') else: form = UserCreationForm() return render(request, 'users/register.html', {'form': form}) and this is the register template {% extends "myblog/base.html" %} {% block content %} <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4"> Join Today! </legend> {{ form.as_p }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit"> Sign Up! </button> </div> </form> <div class="border-top pt-3"> <small class="text-muted"> Already Have an account? <a href="#" class="ml-2">Sign In!</a> </small> </div> </div> {% endblock content%} And this is the file structure of the project File Structure -
Django function missing 1 required positional argument despite its indication
i have the following two functions for outputting my views. Unfortunately, the variable test is not output but, the following error message is output: TypeError: selection() missing 1 required positional argument: 'test' index view def index(request): if request.method != 'POST': return render(request, './views/index.html') else: return redirect('selection', test=234) selection view def selection(request, test): print("TEST: ", test) return render(request, './views/selection.html') -
django restframework how to edit POST form
im working on api that resizes images. I want to upload just one file save it and resize and keep it in another folder. more on image HTML form asks me for 2 files, but I need to upload just one -
How can I access end points of Angular Application after deployment?
I have developed one app in Angular and it's running at local server very fine. Now, I have uploaded same app "Dist" folder to my server (linux) having WSGI + Apache server. I also run Django as backend server framework. I am doing this first time. I have made changes in Django and added index.html. The App is displaying only index.html just like local server. However, how can I access routes further? or end points? Any step by step guidance is available with full application? As mentioned, the app is working fine at local server with routes. http://localhost:4200/ or I want same with, http://my domain/end points Right now my domain is rightly pointing to index.html using Django framework. I have also inspected the page. There is no error in loading the page. Now only question is to access further routes- App module, and another modules. -
handling request priority in web sites
as a newbie in web programming i have an web project with a library study area rezervation system. i am doing the project with django and bootstrap5. so here is the question. how can i handle the rezervation request that come in the same time. there will be levels between my users like student, lecturer and guest. i want to give priority to student. also how can handle giving priority to between users who is in same level, is it (in same level prioritize) something i could do or does server decide what will be? if you give me any idea or title for search I would appreciate it. -
Passing a JSON object from Django to Javascript doesn't work properly
I need to pass a json object to a javascript script in Django. I used the method described here: Django: passing JSON from view to template Here is my view: def test_json(request): data = {} data['key'] = 'value' json_data = json.dumps(data) return render(request, 'test_json.html', {'json_data':json_data}) And my template: {{ json_data|json_script:"json_data" }} <script> const mydata = JSON.parse(document.getElementById("json_data").textContent); const keys = Object.keys(mydata); console.log(keys); </script> But the console output is this: [ "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15" ] It is like it doesn't recognize the keys but recognize every character of the json object as a key, it is like is not recognizing the JSON structure. If I change the script in the template like this: {{ json_data|json_script:"json_data" }} <script> // const mydata = JSON.parse(document.getElementById('json_data').textContent); //const keys = Object.keys(mydata); //console.log(keys) let text = '{ "employees" : [' + '{ "firstName":"John" , "lastName":"Doe" },' + '{ "firstName":"Anna" , "lastName":"Smith" },' + '{ "firstName":"Peter" , "lastName":"Jones" } ]}'; const obj = JSON.parse(text); const keys1 = Object.keys(obj); console.log(keys1) </script> Output: [ "employees" ] I get the key properly. It is like in the process of feeding the JSON from Django to the template the problem. …