Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Distinct values on annotated field using ArrayAgg
I'm trying to annotate to queryset field containing list of user account uuids interested and not interested in participation in some kind of event. This project uses Django 1.11 and PostgreSQL, so i wanted to annotate this list using ArrayAgg. Sadly this version of Django does not support distinct kwarg on ArrayAgg so list I'm getting back contains duplicated elements. Things that I have tried: Using properties on model - this works well and results are good, but instead of 2 queries in 10ms it does ~300 queries in 200ms. It's on development DB so it will be much more noticable on production. Implementing my own ArrayAgg and Aggregate using code from Django 2.0 repo and it works well, I'm getting desired 2 queries, but is there better way so I can evade such "hacky" solution? I can't update Django to version 2.0 Code example: It's version with displayed duplicates models.py import uuid as uuid from django.db import models class Account(models.Model): uuid = models.UUIDField(default=uuid.uuid4) class MyUser(models.Model): account = models.OneToOneField(Account, on_delete=models.CASCADE) class InterestStatus(models.Model): name = models.CharField(max_length=100) interested = models.ManyToManyField(MyUser, related_name='interested') not_interested = models.ManyToManyField(MyUser, related_name='not_interested') @property def interested_users_uids(self): ids = [] for user in self.interested.all(): ids.append(user.account.uuid) return ids @property def not_interested_users_uids(self): ids … -
Django - crispy forms not rendering in the browser
I'm new to django and I'm working on a blog project, but the browser does not render my form on the profile page. Specifically the form to update an profile image. Here's my code: forms.py class UserRegisterForm(UserCreationForm): email = forms.EmailField() # A class to specify the model the form is going to interact with class Meta: model = User # Fields wanted in the form and in what order: fields = ['username', 'email', 'password1', 'password2'] # A model form is a form that allows the creation of a form that will work with a specific database model class UserUpdateForm(forms.ModelForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email'] class ProfileUpdateForm(forms.ModelForm): class Meta: model = Profile fields = ['image'] views.py def register(request): # If it gets a POST request then it instantiates a user creation form with that POST data if request.method == 'POST': # Create a form that has the request POST data: form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, 'Your account was created. You are now able to log in') return redirect('login') # With any other request it creates an empty user creation form else: form = UserRegisterForm() return render(request, 'users/register.html', {'form': form}) … -
Adding a model object and removing one from a different class via single request in Django Admin
It is my first time writing a django application and while I dive in the documentation I was hoping for more experienced suggestions. The models I'm working with are the following: Django Models The intended functionality is as follows - An admin populates the fields and if the 'featured' field is enabled, the 'replace with' field is shown. The 'replace with' field has the objects of the other class 'NewsFeatured'. When submitted: the object from the 'replace with' field is removed from 'NewsFeatured' the object from class 'News' is added to both 'News' and 'NewsFeatured' What I thought of is making a preflight request with javascript when submitting the form with a custom handler in my views and the Django ORM, but I was hoping I can do it from the same request - POST /admin/app/news/add I am trying to figure out the part of code in Django/Core that handles models in the admin site but any help would be appreciated! -
Django - ModelForm has no model class specified
Django is giving me the following error: ModelForm has no model class specified Traceback Traceback (most recent call last): File "C:\Users\Laila\.virtualenvs\BlogProject-71CaIFug\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\Laila\.virtualenvs\BlogProject-71CaIFug\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Laila\.virtualenvs\BlogProject-71CaIFug\lib\site-packages\django\contrib\auth\decorators.py", line 23, in _wrapped_view return view_func(request, *args, **kwargs) File "D:\Programming\Python\Projects\Django\BlogProject\django_project\users\views.py", line 35, in profile userUpdateForm = UserUpdateForm() File "C:\Users\Laila\.virtualenvs\BlogProject-71CaIFug\lib\site-packages\django\forms\models.py", line 356, in __init__ raise ValueError("ModelForm has no model class specified.") Exception Type: ValueError at /profile/ Exception Value: ModelForm has no model class specified. Here's my code: forms.py from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from .models import Profile class UserRegisterForm(UserCreationForm): email = forms.EmailField() # A class to specify the model the form is going to interact with class Meta: model = User # Fields wanted in the form and in what order: fields = ['username', 'email', 'password1', 'password2'] # A model form is a form that allows the creation of a form that will work with a specific database model class UserUpdateForm(forms.ModelForm): model = User fields = ['username', 'email'] class ProfileUpdateForm(forms.ModelForm): class Meta: model = Profile fields = ['image'] views.py from django.shortcuts import render, redirect from django.contrib import messages from .forms import UserRegisterForm, UserUpdateForm, … -
Django Set foreign key field in model from the url parameter
I have a foreign key field in my model which should be set from the url params when the model is saved.I need to set the field automaticatically from the registration-id models.py class Mymodel(BaseModel): name = models.CharField() created_by = models.ForeignKey( 'User', related_name='', null=True, blank=True, on_delete=models.SET_NULL ) last_edited = models.DateField(auto_now=True) registration = models.ForeignKey( SomeModel, related_name='', null=True, blank=True, on_delete=models.SET_NULL ) views.py class MyCreateView(LoginRequiredMixin, CreateView, CustomPermissionMixin): form_class = '' pk_url_kwarg = '' template_name = 'c.html' def form_valid(self, form): form.instance.created_by = self.request.user.person return super().form_valid(form) def get_success_url(self): return reverse('') forms.py class MyModelForm(forms.ModelForm): class Meta: model = Mymodel fields = ('name',) urls.py '<int:registration_id>/employee/create/' -
Can’t install Pillow to deploy a Django web app to AWS beanstalk
I am trying to deploy A django app to beanstalk and I get some errors related to python and requirements.txt and I can't figure out what to do, Any help is appreciated. Here are the errors I get: (the logs are in pastebin bellow) ERROR Instance: i-0e7826c4558b1d21a] Command failed on instance. Return code: 1 Output: (TRUNCATED)...) File "/usr/lib64/python2.7/subprocess.py", line 190, in check_call raise CalledProcessError(retcode, cmd) CalledProcessError: Command '/opt/python/run/venv/bin/pip install -r /opt/python/ondeck/app/requirements.txt' returned non-zero exit status 1. Hook /opt/elasticbeanstalk/hooks/appdeploy/pre/03deploy.py failed. For more detail, check /var/log/eb-activity.log using console or EB CLI. 2022-04-28 15:13:52 UTC+0000 ERROR Your requirements.txt is invalid. Snapshot your logs for details. logs: https://pastebin.com/g1uZLqur here is my requirements.txt Django==2.2.6 django-environ==0.4.5 pytz==2019.3 sqlparse==0.3.0 django-paypal==1.0.0 https://github.com/darklow/django-suit/tarball/v2 git+https://github.com/nn3un/reportlab-mirror#egg=reportlab boto3==1.4.4 django-storages==1.8 psycopg2 django-guardian bokeh==1.4.0 django-ses==2.0.0 mock -
fetching image using django-graphql-vue3 apollo
Is it possible to query image or upload any file on local storage using django backned and vue3 apollo4 through graphql? Does anyone have any reference or tutorial that might help me understand this? Please provide me the link if you have one. Thanks a lot. -
django returns MultiValueDictKeyError at / 'q'
django returns MultiValueDictKeyError at / 'q' in my dashboard template when I'm trying to add search functionality into my app. I want when a user type something on the search input to return the value that user searched for. but i endup getting an error when i try to do it myself. MultiValueDictKeyError at / 'q' def dashboard(request): photos = Photo.objects.all() query = request.GET['q'] card_list = Photo.objects.filter(category__contains=query) context = {'photos': photos, 'card_list':card_list} return render(request, 'dashboard.html', context) <div class="container"> <div class="row justify-content-center"> <form action="" method="GET"> <input type="text" name="q" class="form-control"> <br> <button class="btn btn-outline-success" type="submit">Search</button> </form> </div> </div> <br> <div class="container"> <div class="row justify-content-center"> {% for photo in photos reversed %} <div class="col-md-4"> <div class="card my-2"> <img class="image-thumbail" src="{{photo.image.url}}" alt="Card image cap"> <div class="card-body"> <h2 style="color: yellowgreen; font-family: Arial, Helvetica, sans-serif;"> {{photo.user.username.upper}} </h2> <br> <h3>{{photo.category}}</h3> <h4>{{photo.price}}</h4> </div> <a href="{% url 'Photo-view' photo.id %}" class="btn btn-warning btn- sm m-1">Buy Now</a> </div> </div> {% empty %} <h3>No Files...</h3> {% endfor %} </div> </div> -
How can I Generate 10 Unique digits in Model Form and Pass Form Context Variable in Django Class Based ListView
I am new to Django Class Based Views and I am working on a project where on the template I want to have Form for creating customer accounts on the left and list of existing customers on the right. So far I have the list of existing customers displayed but for the form I don't know how to pass its variable context to the same template, or it is not possible to Pass a Form that would be submitted inside a ListView Method. And I also want to generate unique account numbers of 10 Digits in ModelForm which I want the form field to be auto-filled and disabled Here is my form code: import secrets #I want to Generate Account Number of 10 Digits but getting only 2 account = secrets.randbits(7) #class for Customer Account Form class CustomerAccountForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().init(*args, **kwargs) self.fields['accountnumber'].initial = account class Meta: model = Customer fields = ['accountnumber','surname','othernames','address','phone'] Code for my views (ListView) class CustomerListView(ListView): model = Customer form_class = CustomerAccountForm template_name = 'dashboard/customers.html' #Function to get context data from queries def get_context_data(self, **kwargs): context_data = super().get_context_data(**kwargs) #Get Day of today from current date and time now = datetime.datetime.now() #Get the date today … -
Django backend on aws lambda : what is considered a request?
Im considering setting up a django backend on aws lambda and i need to calculate the costs based on the number of requests and duration of these requests. How can I calculate the number of requests in django (ie what is considered in django as an aws lambda request)? Is a page requested equivalent to a request in aws lambda? Or is a database access equivalent to one request ? How can I compute the average duration of a request? THank you -
when I print @property value it return this <property object at 0xffff906b2048>
I am working on Django serve, my question is How I can print a actual value of this file modles.bookings.py @property def grand_total_amount_display(self) -> str: return format_currency_amount(self.grand_total_amount, self.currency) grand_total_amount_display.fget.short_description = 'Grand Total' util.spaces file def get_booking(): from sook_booking.models.bookings import Booking # circulation-import issue print('Booking.grand_total_amount',Booking.grand_total_amount_display) return str(Booking.grand_total_amount_display) and i am getting this value when I print Booking.grand_total_amount <property object at 0xffff906b2048> -
What type of problem am I having with logging on the website via Facebook?
I'm trying to implement a login on the site via Facebook using allauth. That's logs: 31.13.103.10 - - [11/May/2022:11:11:27 +0000] "GET /accounts/facebook/login/callback/ HTTP/1.1" 200 273 "-" "facebookexternalhit/1.1 (+http://www.facebook.com/externalhit_uatext.php)" "31.13.103.10" response-time=0.026 178.88.74.128 - - [11/May/2022:11:12:00 +0000] "GET / HTTP/1.1" 200 183 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.64 Safari/537.36" "178.88.74.128" response-time=0.007 178.88.74.128 - - [11/May/2022:11:12:03 +0000] "GET /accounts/facebook/login/?process= HTTP/1.1" 200 408 "https://konstantin07.pythonanywhere.com/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.64 Safari/537.36" "178.88.74.128" response-time=0.026 178.88.74.128 - - [11/May/2022:11:12:06 +0000] "POST /accounts/facebook/login/?process= HTTP/1.1" 302 0 "https://konstantin07.pythonanywhere.com/accounts/facebook/login/?process=" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.64 Safari/537.36" "178.88.74.128" response-time=0.036 Everything is ok: 200-200-200-302 But Facebook says that something went wrong: Sorry, something went wrong. We're working on getting this fixed as soon as we can. Go Back How can I find out what was wrong? -
VISUALISATION OF DATA USING DJANGO /POSTGRESQL
i need to create a django app for data visualization , with Database on postgresql I need to obtain a graph (line) for values of 2 columns table_name: "sample" column1 " sampleID" : 4322,45346,765754 column2 " absorbance" : 3232;34325;6547634;346547;342;56546;2434;546458;34354236;566345735, 362482;25346;68465;56347;357548;768746;6574563;436467;9785676321;87834, 986853;285797;5436346;43634567;7547548;345345;4367548;3565634,6347536 We can see that for each sampleID , each value of absorbance it is a succession of differente values Each of this values will be a point in my axe of the graph and i will obtain 3 lines because 3 sampleID ''' How i can create a graph from this type of values ? i really want to use ChartJS because it s very dynamic dor design , someone can help me? -
How to get details from two models in django
I am trying to build an api endpoint that performs a GET request, path -> {url}/api/v1/users/:id I have three models class PvSystem(models.Model): modelNo = models.CharField(max_length=10, blank=False, default='') modelName = models.CharField(max_length=10, blank=False, default='') dimensionPanel: models.FloatField(max_length=10, blank=False, default=NULL) elevation = models.FloatField(max_length=10, blank=False, default=NULL) kwhPeak = models.FloatField(max_length=10, blank=False, default=NULL) avergaeSurplus = models.FloatField(max_length=10, blank=False, default=NULL) class EnergyData(models.Model): pvId = models.ForeignKey(PvSystem,related_name='orders',on_delete=models.CASCADE) energyNeeded = models.FloatField(max_length=10, blank=False, default=NULL) energyConsumption = models.FloatField(max_length=20, blank=False, default=NULL) energyProduction = models.FloatField(max_length=20, blank=False, default=NULL) energySurplus = models.FloatField(max_length=20, blank=False, default=NULL) floorPrice = models.FloatField(max_length=10, blank=False, default=NULL) capPrice = models.FloatField(max_length=10, blank=False, default=NULL) pvStatus = models.BooleanField(blank=False, default=False) dsoId = models.CharField(max_length=70, blank=False, default='') supplier = models.CharField(max_length=70, blank=False, default='') class User(models.Model): name = models.CharField(max_length=70, blank=False, default='') email = models.EmailField(max_length=70, blank=False, default='') password = models.CharField(max_length=70, blank=False, default='') address = models.CharField(max_length=70, blank=False, default='') roleId = models.IntegerField(blank=False, default='1') isActive = models.BooleanField(blank=False, default=TRUE) dsoId = models.CharField(max_length=70, blank=False, default='') supplier = models.CharField(max_length=70, blank=False, default='') dateJoined = models.DateTimeField(auto_now_add=False, blank=False, default=NULL) Models Description UserModel: Registered details of the user. EnergyData: A table that provides more details of the user using the users dsoID and supplier to check. PVSystem: Connected to the Energydata hence return result of a user with energy data and pvstatus TRUE. From the above, when the api get request call is made, it … -
Django Framework : i do not understand how to show my data into my homepage.views from polls.views
thanks for reading ! I got some trouble to understand how to display my polls.views into my homepage.views. this is the code not working into my homepage_index.html : {% if latest_question_list %} <ul> {% for question in latest_question_list %} <li><a href="{% url 'polls:detail.html' question.id %}">{{ question.question_text }}</a></li> {% endfor %} </ul> {% else %} <p>No polls are available.</p> {% endif %} The same code working on his own application named polls and i fail to repeat this same thing into my homepage This is my homepage/urls.py : from django.urls import path, re_path from django.conf.urls import include from . import views app_name = 'homepage' urlpatterns = [ path('', views.homepage.as_view(), name='homepage'), ] and this is my homepage/views.py : from django.views import generic from django.utils import timezone from blog.models import Article class homepage(generic.ListView): template_name = 'homepage/homepage_index.html' context_object_name = 'latest_article_list' def get_queryset(self): return Article.objects.filter( pub_date__lte=timezone.now() ).order_by('-pub_date')[:20] When i launch my local server, go to homepage_index.html, i got the message : No polls are available. I miss something and i dont know what or where, its look like the access to the DATA are failing. I'm sorry if I misunderstood the situation, let me know if you want more details, thank you! -
How i can make condition readonly on some fields based on what i choose on foreignkey field (the fields exist on same model) : Django-admin
I have modelA contain field1(foreignkey), field2(float) and other fields(all are float) I would like to makes the some other fields readonly(not editable) depend on what i choose on the field1(foreignkey) and to be clear all those fields are in same model. I would like to do that on django-admin: Here my models.py: class Modele(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='sizes',null = True) w_profile = models.FloatField(null=True) b = models.FloatField(null=True, blank=True) tw = models.FloatField(null=True, blank=True) tf = models.FloatField(null=True, blank=True) Here my admin.py: admin.site.register(ProfileSize) class ModeleAdmin(admin.ModelAdmin): def __init__(self, *args, **kwargs): super(Modele, self).__init__(*args, **kwargs) if self.category.name == "Flate": return self.readonly_fields + ('tw', 'b') elif self.category.name == "Circular": return self.readonly_fields + ('b') else: return self.readonly_fields + ('tf') But what i have on admin.py didn't give me any result , any help will be appreciated.thanks. -
How do I associate a python file with the django web interface?
I have a Python code for the A* algorithm. And I want to modify it so that the user is the one who enters the names of cities, longitude and latitude and link it to the django web interface But I don't know these steps Please helpdownload file code A* Thanks -
I am creating a search function in django but it isn't working
I am trying to create a function to search for objects in base.html from the database using a keyword and printing the results in listing.html base.html <form method="post" action="{% url 'listing'}" name="searchform"> {% csrf_token %} <div class="custom-form"> <label>Keywords </label> <input type="text" placeholder="Property Keywords" name="search_keyword" value=""/> <label >Categories</label> <select data-placeholder="Categories" name = "home_type" class="chosen-select on-radius no-search-select" > <option>All Categories</option> <option>Single-family</option> <option>Semi-detached</option> <option>Apartment</option> <option>Townhomes</option> <option>Multi-family</option> <option>Mobile/Manufactured</option> <option>Condo</option> </select> <label style="margin-top:10px;" >Price Range</label> <div class="price-rage-item fl-wrap"> <input type="text" class="price-range" data-min="10000" data-max="100000000000" name="price-range1" data-step="1" value="1" data-prefix="$₦"> </div> <button onclick="location.href='listing'" type="button" class="btn float-btn color-bg"><i class="fal fa-search"></i> Search</button> </div> </form> views.py def listing(request): global search_keyword p = Paginator(Property.objects.order_by('-listed_on'), 2) page = request.GET.get('page') propertys = p.get_page(page) nums = "p" * propertys.paginator.num_pages if request.method == 'POST' and 'searchform' in request.POST : search_keyword = request.POST['search_keyword'] propertys = Property.objects.filter(name__contains=search_keyword) return render(request, 'listing.html',{'nums':nums, 'search_keyword':search_keyword, 'propertys':propertys}) return render(request, 'listing.html',{'nums':nums,'propertys':propertys}) -
How to parse years of experience from resume from Experience field present in resume?
I am working with a resume parser in Django that can parse all the data but I want to calculate years of experience from the dates mentioned in the resume in the experience field I have come up with a strategy that we can parse the experience section and parse all the dates but I am facing a hard time to implement it. Is there any other way to calculate the experience from different dates and add all the dates? def extract_experience(resume_text): ''' Helper function to extract experience from resume text :param resume_text: Plain resume text :return: list of experience ''' wordnet_lemmatizer = WordNetLemmatizer() stop_words = set(stopwords.words('english')) # word tokenization word_tokens = nltk.word_tokenize(resume_text) # remove stop words and lemmatize filtered_sentence = [w for w in word_tokens if not w in stop_words and wordnet_lemmatizer.lemmatize(w) not in stop_words] sent = nltk.pos_tag(filtered_sentence) # parse regex cp = nltk.RegexpParser('P: {<NNP>+}') cs = cp.parse(sent) # for i in cs.subtrees(filter=lambda x: x.label() == 'P'): # print(i) test = [] for vp in list(cs.subtrees(filter=lambda x: x.label()=='P')): test.append(" ".join([i[0] for i in vp.leaves() if len(vp.leaves()) >= 2])) # Search the word 'experience' in the chunk and then print out the text after it x = [x[x.lower().index('experience') + 10:] … -
use js variable in Django
userlist.html <a id="{{user.id}}" href="/followerPosting?id={{following.id}}" class="btn">profile</a> I want to pass the id value to the url when the btn is clicked. followerPosting.html <script type="text/javascript"> var url = require('url'); var queryData = url.parse(request.url, true).query; var fid = queryData.id; </script> So I parsed the URL and stored the id value in a variable (fid). {% for twit in twits %} {% if twit.User.id == fid %} <div class="twit"> <div class="twit-content">{{twit.content}}</div> </div> {% endif %} {% endfor %} I want to use this variable in html (django) how can I use this value? I tried to use Ejs but it didn't work well... -
filefield serializer is not parsing the file object
I have a model in my application: class GRNRFIDSerials(models.Model): grn = models.ForeignKey(Grn, on_delete=models.CASCADE) file = models.FileField(upload_to='grnrfid/', null=True, blank=True) owner = models.ForeignKey(User, on_delete=models.CASCADE) I am trying to upload the file in the ORM like the following: class GRNRFIDSerialsUploadAPIView(CreateAPIView): permission_classes = (permissions.IsAuthenticated, ) serializer_class = GrnRFIDSerialsSerializer parser_classes = (FormParser, MultiPartParser) def post(self, request, *args, **kwargs): owner = request.user.pk print("reached") d = request.data.copy() d['owner'] = owner print("d", d) serializer = GrnRFIDSerialsSerializer(data=d) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) where d is : d <QueryDict: {'no_of_fileA_files': ['1'], 'grn': ['479'], 'viewType': ['Pool Operator'], 'companyId': ['52'], 'document': [<InMemoryUploadedFile: EPC (4).xlsx (application/vnd.openxmlformats-officedocument.spr eadsheetml.sheet)>], 'owner': [27]}> This runs without an error but n the database entry filefield is shown as blank. How do I upload the file object? -
Is it good practice to do integration testing on Django's admin section?
I know StackOverflow discourages 'opinion-based' questions, but this seems very basic and I'm surprised by the lack of info on it. Normally I would think of some kind of Selenium test for any UX as mandatory, but the Django testing docs don't mention anything of the sort, and Googling for 'Django admin integration test' and similar isn't highlighting anything about the admin section. Do people just tend to unit test the admin.py subclasses and leave it at that, assuming the rest is covered by the framework? -
I just pip installed social-auth-app-django==3.1.0 and I got the error below
I just pip installed social-auth-app-django==3.1.0 and I got the error below while trying to migrate. ImportError: cannot import name 'force_text' from 'django.utils.encoding' (C:\Users\Hp\anaconda3\lib\site-packages\django\utils\encoding.py) -
how to write unit test using pytest for django url
my url and function are as follows url path('drivers/', views.drivers, name='drivers'), views.py @login_required(login_url='/account/login') def drivers(request): drivers = Drivers.object.all() return render(request, "drivers.html", {'drivers': drivers}) I've just started learning unit testing. How do i write unit test to check my url is working as expected. -
Nasa API pass the data so slow
I'm trying to get near-earth asteroid data from NASA API. And I'm getting the data I need but it's coming very slow. How can I optimize my code to get data quickly? @api_view(['GET']) def getDates(request, start_date, end_date): dates = [] all_data = list() api_key = 'hpdCBykg6Bcho1SitxAcgAaplIHD1E0SzNLfvTWw' url_neo_feed = "https://api.nasa.gov/neo/rest/v1/feed?" params = { 'api_key': api_key, 'start_date': start_date, 'end_date': end_date } response = requests.get(url_neo_feed, params=params) json_data = orjson.loads(response.text) date_asteroids = json_data['near_earth_objects'] for date in date_asteroids: dates.append(date) # Splitting the data to make it more meaningful for date in dates: collection = json_data.get('near_earth_objects') all_dates = collection.get('{}'.format(date)) all_data.append(all_dates) return Response(all_data)