Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Does django transaction.non_atomic works in management scripts?
I would like to update every entry in a single transaction. For that reason I wrote following management script: class Command(BaseCommand): help = 'perform health check on all instances' def printit(self): print('commited...') @transaction.non_atomic_requests def handle(self, *args, **options): # perform health check and data collection on all known servers print('Performing health checks...') for instance in Instance.objects.all(): with transaction.atomic(): instance.collect_stats() transaction.on_commit(self.printit) In the documentation @transaction.non_atomic_reqeuests can be activated for views. Does this option effect also management scripts? -
How close does a database need to be to the application to get decent performance?
A bit of an odd problem. I've literally lifted code from one tests.py page to another (test_main.py and copied code to test_models.py), including copying the imports at the top of the page, but the data feature works on one page but not the other. I'm also not understanding the difference between import xxxx and from xxx import xxx. from django.test import TestCase from journal.models import Ledger, COAGroup, JournalEntry, Project, LineItem from decimal import Decimal from django.urls import reverse from datetime import datetime from dateutil.relativedelta import relativedelta from django.contrib.auth.models import User Line that fails: journal_entry = JournalEntry(user=User.objects.get(pk=1), date=datetime.date.today(), type="JE", description='Test journal entry') Fail message: ====================================================================== ERROR: test_is_reconciled (journal.tests.test_models.LedgerTest) Check that is_reconciled() gives correct response ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\Users\Philip\CodeRepos\Acacia2\journal\tests\test_models.py", line 24, in test_is_reconciled journal_entry = JournalEntry(user=User.objects.get(pk=1), date=datetime.date.today(), type="JE", description='Test journal entry') AttributeError: 'method_descriptor' object has no attribute 'today' ---------------------------------------------------------------------- -
How to loop multiple form fields in a table then submit
Ideally i am working on attendance of members, On a given date, members who have attended are roll called, then their status submitted at once in the attendance table. here is my code views.py def make_attendence(request): if request.method=="POST": form=AttendanceForm(request.POST, request.FILES,) if form.is_valid(): form.save() messages.success(request, f'Members Attendance For Today has been Made') return redirect('attendence-history') else: form=AttendanceForm() all_members=CustomUser.objects.all() context={'form':form, 'all_members':all_members} return render(request,'make_attendance.html',context) make_attendance.html <form method="POST" enctype="multipart/form-data" > {% csrf_token %} {% load crispy_forms_tags %} <table id="data-table" class="table table-striped table-bordered dt-responsive nowrap" cellspacing="0" width="100%"> <div class="col-lg-4 form-group"> <label for="date">Date:</label> <input type="date" name="date" class="form-control" id="date" required="*" > </div> <thead> <tr style="font-weight: bolder;"> <td>Name</td> <td>Attendance</td> <td>Social fund</td> </tr> </thead> <tbody> {% for member in all_members %} <tr> <td>{{member.full_name}}<input type="hidden" id="full_name" name="full_name" value="{{member.full_name}}"></td> <td>{{form.status}}</td> <td>{{form.social_fund}}</td> </tr> {% endfor %} </tbody> </table> <button type="submit" class="btn btn-primary" >Submit</button> </form> The problem am facing is that on submit, only one record is saved in the attendance table. Any help is highly appreciated. -
Random Number Guesser using Django-Python
I want to Implement a Number Guessing Game using Django. However, I am facing issues since with every guess since it gets reloaded and therefore the number changes. Any Suggestions? def RanNum(request): number = random.randint(1,20) print('Ans:',number) if request.method=="POST": guess=request.POST['Guess'] num_guesses = 0 guessed_number= False while not guessed_number: if not is_valid_num(guess): messages.info(request,"A number between 1 and 20 ony (Not Counted):") return redirect('/game') continue else: num_guesses +=1 guess = int(guess) if guess < number: messages.info(request,"Too LOW.Guess again:") return redirect('/game') elif guess > number: messages.info(request,"Too HIGH.Guess again:") return redirect('/game') else: messages.info(request,"No of Guesses:") messages.info(request,num_guesses) return redirect('/game') guessed_number = True messages.info(request,"thanks for playing") return render(request,template_name='html/RandomNumApp/Ran.html',) else: return render(request,template_name='html/RandomNumApp/Ran.html',) -
Django: pagination with prefetch_related
I have a model specifications which are divided into categories. For the template, in order to display the category as an header in the table, I make a prefetch_related on the Category like this: categories = Category.objects.distinct().prefetch_related('specifications').filter(filters) Now I can loop over the categories and show the related specifications like: {% for category in categories %} <tr> <th colspan="7">{{ category.name }} - ({{ category.abbr }})</th> </tr> {% for specification in category.specifications.all %} ... I also want to use the paginator, but now the paginator only counts the categories and not the related specifications. Is it possible to paginate on the specifications with the given query or should I change the query to retrieve all the specifications? -
How to set 2 attributes to primary key together in Django?
I have a model in Django: class Subject(models.Model): level = models.CharField(max_length=50) subject_name = models.CharField(max_length=50) teacher_name = models.ForeignKey(Teacher, on_delete=models.CASCADE) total_seats = models.IntegerField() subject_details = models.CharField(max_length=50) For the Subject table I want the level and the subject_name together to be primary keys. In fact, I dont want any other objects to have the same name and level. I know I can use unique_together but where do I mention the primary_key = True? -
Python Official Stripe Client Creating Two Customers
This code I'm using below works perfectly, except when checkout is complete I have noticed two customer entries are being made every time someone checkouts on my site. One has the default source set and one does not. I have attached a screenshot. https://i.ibb.co/8dd0Cxz/Screenshot-from-2020-04-20-11-15-25.png @login_required def checkout(request): if request.method == 'POST': plan = Plan.objects.get(nickname=request.POST['plan']) stripe_customer = stripe.Customer.create( email=request.user.email, source=request.POST['stripeToken']) stripe_subscription = stripe.Subscription.create(customer=stripe_customer.id, items=[ {'plan': plan.id}], trial_from_plan=True) Subscription.sync_from_stripe_data( stripe_subscription ) return redirect('settings') else: if request.method == 'GET': plan = Plan.objects.get(nickname=request.GET['plan']) return render(request, 'plans/checkout.html', {'plan': plan, 'price': '0'}) I have tried changing {'plan': plan.id} to {'plan': plan} and I get error: Request req_0WL0lW2orGwLMV: No such plan: Family; one exists with a name of Family, but its ID is plan_H5fvA8jJ0qX9qF. -
WebGL warning: texImage: Alpha-premult and y-flip are deprecated for non-DOM-Element uploads
So I have been trying to use Map-box to plot coordinates in my App, but when I provide the .png file to act as marker, i get this following error: WebGL warning: texImage: Alpha-premult and y-flip are deprecated for non-DOM-Element uploads. Screenshot -
How to get different data in queryset ForeignKey?
This is one of my models: class MyModel(models.Model): field_1 = models.ForeignKey(Table_1, related_name='some_name') field_2 = models.ForeignKey(Table_2, related_name='other_name') # other fields The queryset I get for this model contains id for the Foreign Keys. I want to get unique_id instead. I tried using .values, but it didn't solve the purpose, because it returns dicts, but I require the model objects instead. So what should I do to get unique_id in the queryset object? -
Issue with Django filtering
I have a problem with my code and I don't know how to fix it! I used Django Filters and Django Tables 2 to build a filterable list from a db table. The filter in itself works fine, but I found out that if I leave all filters empty I get the entire table on the web page, while in this case I want zero results. Any suggestion / advice would be greatly welcomed! See code below: tables.py from .models import Casualty import django_tables2 as tables from django_tables2 import TemplateColumn from django_tables2.utils import A class CasualtyTable(tables.Table): edit = TemplateColumn(template_name='casualties_update_column.html', verbose_name='') delete = TemplateColumn(template_name='casualties_delete_column.html', verbose_name='') def before_render(self, request): if request.user.has_perm('casualty.change_bar'): self.columns.show('edit') else: self.columns.hide('edit') if request.user.has_perm('casualty.delete_bar'): self.columns.show('delete') else: self.columns.hide('delete') class Meta: model = Casualty exclude = ('author', 'added_by', 'updated_by', 'date_created', 'date_updated') attrs = {"class": "casualties" , "style": "overflow-x:auto;"} filters.py import django_filters from .models import Casualty class CasualtyFilter(django_filters.FilterSet): first_name = django_filters.CharFilter(label = 'First Name', lookup_expr='contains') last_name = django_filters.CharFilter(label = 'Last Name', lookup_expr='contains') middle_name = django_filters.CharFilter(label = 'Middle Name', lookup_expr='contains') ref_nr = django_filters.CharFilter(label = 'Ref Nr', lookup_expr='contains') service_nr = django_filters.CharFilter(label = 'Service Nr', lookup_expr='contains') rank = django_filters.CharFilter(label = 'Rank', lookup_expr='contains') regiment = django_filters.CharFilter(label = 'Regiment', lookup_expr='contains') how_they_died = django_filters.CharFilter(label = 'How Died', lookup_expr='contains') date_of_death … -
how to optimize the query here with select_related?
i have class A(models.Model): field_a = models.OneToOneField(B, on_delete=models.CASCADE) class B(models.Model): field_b = models.charField() how to write the most optimum query here using select_related or something else? My use case is to get the field_a of model A. queryset_b = B.objects.get(field_b="some name") queryset_a = A.objects.get(b=queryset_b).field_a it hits the db twice. Can i do this thing in one db hit using select_related? -
How Can I Use Django 3 with MongoDB?
Is there a way that I can use Django 3 + MongoDB because djongo (the package which integrates MongoDB and Django) requires Django 2.x. Note that I don't want to move to Django 3 for specific reasons. I just wanna explore it. and I need MongoDB because I am writing a data analysis web app (since NoSQL Databases Perform well when working with large data sets). thanks in advance. -
Unable to add User to new Group in Django unittest
Adding a User to a new Group (in a Django unittest) results in Django.core.exceptions.FieldError This exception has got me stumped. I am merely writing the following unittest as an example to learn the Django unittest system before I use the rest_framework APITestCases. TLDR; I have reset my environment, tested in the Django debug interactive environment with the same code and attempted to add the user multiple ways. The unittest still fails, the debug shell still works... Details I wrote the following test (for conscientiousness I omitted the assert statements...) class modelsTests(TestCase): def testUserModel(self): # we should begin with no users... self.assertEquals( User.objects.count(), 0 ) # create some demo users, 2 exactly... User.objects.create(username="test user", email="test@unittest.com") # add the first user to a group, not the second Group.objects.create(name="Test") user = User.objects.first() user.groups.add(Group.objects.get(name="Test")) # create the second user without any groups User.objects.create(username="another user", email="anothertest@unittest.com") I then run the test (which includes several assert statements after the snippet) with, py manage.py test testdrivendevelopment.tests This returns the following error code and stack trace, Creating test database for alias 'default'... System check identified no issues (0 silenced). F.E ====================================================================== ERROR: testUserModel (testdrivendevelopment.tests.test_models.modelsTests) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\Users\alber\OneDrive - UTS\UTS\ProgSoc\TDD workshop\testdrivendevelopment\tests\test_models.py", line 40, in … -
Сreate a full copy of the object from UpdateView or from ListView in Django
I have Class Based views for my models. I want to create a full copy of the object and go to editing it. I would like to do this from UpdateView with a special button for copying, but it is a good option from the list of objects. How can I do this? Below is the code for one of the models. My ListView: class KeysView( LoginRequiredMixin, CustomPermissionRequired, ListView, ): model = ApiKey context_object_name = 'apikey' paginate_by = 20 template_name = 'db_visual/apiKeys.html' def get_queryset(self): filter_kwargs = {} filter_args = [] search = self.request.GET.get('search', '') if search: filter_args.append( Q(description__icontains=search) | Q(id__icontains=search) ) return ApiKey.objects.filter(*filter_args, **filter_kwargs) \ .order_by('-id') def get_context_data(self, **kwargs): context = super(KeysView, self).get_context_data(**kwargs) context['search'] = self.request.GET.get('search', '') return context My UpdateView: class UpdateKeyView( SuccessMessageMixin, CustomPermissionRequired, UpdateView ): model = ApiKey pk_url_kwarg = 'apikey_id' template_name = 'db_visual/update_key.html' form_class = KeyForm success_url = reverse_lazy('keys') success_message = "Ключ <a href='%(url)s'>%(description)s</a> " \ "успешно изменен!" def get_success_message(self, cleaned_data): return self.success_message % dict( cleaned_data, url=reverse_lazy( 'update_key', kwargs={'apikey_id': self.object.id} ), ) -
Django ForeignKey Which field?
I have just started learning Django and one thing in models about ForeignKey was unclear to me. So lets say I have one model like this: class Webpage(models.Model): name = models.CharField(max_length=264, unique=True) url = models.URLField(unique=True) name2 = models.CharField(max_length=264, unique=True) class Records(models.Model): site = models.ForeignKey(Webpage) So when creating Records entry for testing I see ForeignKey is referenced to Name field of Webpage. My confusion is why exactly name? As I know ForeignKey is referencing to primary key and if you are not giving primary_key attribute to any fields it will create 'id' field and make that as primary_key. So then why not 'id' field but 'name'. Sorry if this is repeat question, I just couldn`t find answer. -
What are efficient ways to return data from an sql database wich is ordered depending on an other service?
I have a database serving a huge and highly normalized resource and an API serving customized recommendation for every items in this database. I want to be able to give a paginated list of items matching search criteria and ordered depending on the recommendation API. For example if a user searched for bands with the Jazz type I would want to return a list of all of the matching band ordered depending on the results of our recommendation API. Our recommendation API gives a list of all bands with a recommendation score which is unique for each users. The best thing i can think of so far is to get a page of recommendation, and do an ORDER BY CASE query with each band ordered depeding on the result of the recommendation: SELECT "band"."id" FROM "band" WHERE "band"."kind_id" = 42 ORDER BY CASE WHEN ("band"."id" = 123) THEN 100 ... WHEN ("band"."id" = 456) THEN 1 ELSE 0 END DESC LIMIT 100 In django this same query looks like this: search = {"kind__name": "Jazz"} recommendations = [ When(id=api_response["id"], then=Value(api_response["score"])) for api_response in api_responses ] queryset = ( Band.objects.annotate( recommendations=Case( *recommendations, default=Value(0), output_field=IntegerField(), ) ) .filter(**search) .order_by("-recommendations")[0:100] ) Then do the … -
Wsgi script and the newest django with Python 3.5
We are trying to deploy one more web-application on our VPS. There is one flask application in production already, which is held by Python 3.5 interpreter. Now we need another one - django app. We have configured our apache2 to host both of then (django is working on subdomain, whereas flask is on the 'root' domain. Everything is okay here. But, since flask application is using global python interpreter (version 3.5) we cannot run django since it requires version 3.6 or newer. Here is django WSGI script: import os import sys print('Python version is ... ') # 3.5 python_home = '/var/www/mysite/venv' activate_this = python_home + '/bin/activate_this.py' exec( open(activate_this).read() ) print(sys.executable) # in case of virtualenv it refers to /usr/bin/python3.5 import logging logging.basicConfig(stream=sys.stderr) sys.path.insert(0,"/var/www/mysite/mysite") from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings") application = get_wsgi_application() We could have upgraded our interpreter to 3.6, but since established flask app is in production we are not allowed to do so by our managers.. And it is okay probably If we go with virtualenv nevertheless it created virtual environment with existing global interpreter , as is written above version 3.5. And this is where we are stuck now. Apache2 log is constanlty saying to us: [wsgi:error] … -
Django - How can I add formset in the tabular format data?
Here is my following code that can adding new rows when populating data in the input fields. <html> <head> <link rel="stylesheet" href="css/bootstrap.min.css"> <link rel="stylesheet" href="css/bootstrap-theme.min.css"> <script type="text/javascript" src="js/jquery-3.5.0.min.js"></script> </head> <body class="container"> <h1 align="center">Module Testing</h1> <form method="post" class="form-inline"> <div align="center"> <input type="text" id="id" name="id" placeholder="ID" class="form-control"> <input type="text" id ="name" name="test_name" placeholder="Test Name" class="form-control"> <input type="text" id="result" name="result" placeholder="Result" class="form-control"> <input type="text" id="units" name="units" placeholder="UOM" class="form-control"> <button type="button" id="btn-add" class="btn btn-info">Add</button> </div> </form> <hr> <form method="post"> <table class="table"> <thead> <tr> <th> #ID </th> <th> Test Name </th> <th> Result </th> <th> UOM </th> </tr> </thead> <tbody> </tbody> </table> <button type="submit" id="btn-submit" class="btn btn-info">Submit</button> </form> <script> $(function(){ $('#btn-add').click(function(){ var id = $('#id').val(); var name = $('#name').val(); var result = $('#result').val(); var units = $('#units').val(); var tr = '<tr><td>'+id+'</td><td>'+name+'</td><td>'+result+'</td><td>'+units+'</td></tr>'; $('tbody').append(tr); }); }); </script> </body> </html> How can I add formset in the above code in order to save all the data in the database in the single click. I'm new to django. Thanks. -
django: How do I test Update View (And form)?
I'm trying to test and Update View which works perfectly fine when using it via the browser. But I want to add more automated tests. Note: This is my first django app. In my class based test case I have implemented setUpwhich generates the needed objects and user. Then I login with the created user and try to update the object: login = self.client.login(username='testuser', password='123456') response = self.client.post( reverse('edit_batch', kwargs={'pk': self.id}), {'project': self.project.id, 'container': self.container.id, 'comment': 'Updated'}) #fails here status_code = 400 (if not debugged) self.assertEqual(response.status_code, 302) The updated field is comment. When I run this, the test fails because status_code is 400. However when I debug through the views and form, for unknown reason then this part doesn't fail and I do get a 302 response. eg. there seems to be some kind of race condition going on. This is already very weird. What am I doing wrong??? When this assert actual does pass due to debugging, I then fail on the next assert which checks if the updated actually happened: self.batch.refresh_from_db() self.assertEqual(self.batch.comment, 'Updated') self.batch.comment remains unchanged (None) and I can see when debugging and the form gets saved the updated field comment is still set to None. Not … -
Django - Python - URL didn't match any of these
When I write code like this without.html in the end of about/: from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('about/', views.about, name='about'), path('contact/', views.contact, name='contact'), path('categories/', views.categories, name='categories'), path('docAdd/', views.docAdd, name='docAdd') ] I get errors when click on about in the navbar of my webpage, error in that case is : " The current path, about.html, didn't match any of these." But when I change about/ to about.html/ then I can click on about in navbar and page opens, but when I switch from about to contact in navbar I get error like: "The current path, about.html/contact.html, didn't match any of these." I can't seem to solve this, please help. This is the code with about.html/: from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('about.html/', views.about, name='about'), path('contact.html/', views.contact, name='contact'), path('categories.html/', views.categories, name='categories'), path('docAdd.html/', views.docAdd, name='docAdd') ] views.py code: from django.shortcuts import render from . models import Document # Create your views here. def index(request): return render(request, 'index.html') def about(request): return render(request, 'about.html') def contact(request): return render(request, 'contact.html') def categories(request): return render(request, 'categories.html') def docAdd(request): return render(request, 'docAdd.html') This is the error: Page not found (404) Request … -
How to fetch when One of ManytoMany member is ON
I have model Machine which has a few switches (many to many). I am making filter to fetch when more than one switch is 'On'. queryset.filter(switchs__is_on=True) does not work. how can I solve this?? class Machine switchs = models.ManyToManyField(Station) class Switch(models.Model): is_on = models.BooleanField() class MachineFilter(filters.FilterSet): on_switch = filters.BooleanFilter(method='on_switch_filter') class MachineFilter(filters.FilterSet): def on_switch_filter(self, queryset, name, value): if name == 'on_switch' and value: return queryset.filter(switchs__is_on=True) // it doesn't work -
Django 1.11 - How to send mails using a mail server which supports NTLM authentication only
I'm using Django 1.11 and want to send mails by using an Exchange 2013 server which only supports NTLM for SMTP authentification. I realized that the default email backend django.core.mail.backends.smtp.EmailBackend only supports LOGIN, PLAIN or CRAM-MD5 for authentication. Luckily, I found another promising backend (https://github.com/shadiakiki1986/django-smtp-ntlm-backend) for SMTP with NTLM authentication. Installation of the backend was successful but it does not work. The following happens at the Python console: >>> from django.core.mail import send_mail >>> send_mail('test subject', 'message', 'email@address.com', ['recipient@gmail.com'], fail_silently=False,) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/local/lib/python2.7/site-packages/django/core/mail/__init__.py", line 62, in send_mail return mail.send() File "/usr/local/lib/python2.7/site-packages/django/core/mail/message.py", line 348, in send return self.get_connection(fail_silently).send_messages([self]) File "/usr/local/lib/python2.7/site-packages/django/core/mail/backends/smtp.py", line 111, in send_messages sent = self._send(message) File "/usr/local/lib/python2.7/site-packages/django/core/mail/backends/smtp.py", line 127, in _send self.connection.sendmail(from_email, recipients, message.as_bytes(linesep='\r\n')) File "smtplib.py", line 736, in sendmail self.rset() File "smtplib.py", line 470, in rset return self.docmd("rset") File "smtplib.py", line 395, in docmd return self.getreply() File "smtplib.py", line 369, in getreply raise SMTPServerDisconnected("Connection unexpectedly closed") smtplib.SMTPServerDisconnected: Connection unexpectedly closed Relevant settings in settings.py: EMAIL_ENABLE=True EMAIL_BACKEND=django_smtp_ntlm_backendNTLMEmail EMAIL_HOST=<mailserver> EMAIL_PORT=25 EMAIL_HOST_USER=<domain>\<user> EMAIL_HOST_PASSWORD=<password> DEFAULT_FROM_EMAIL=<email> EMAIL_USE_SSL=False EMAIL_USE_TLS=False These settings are working fine using a SMTP testing tool called Swaks. Does anybody have experience with using Exchange and NTLM authentication for sending emails … -
Django ForeignKey from external Database
I'm working with 2 Databases, 1 external not managed by Django and the other internal. Thi is the external database now working on models and in Admin site: class Client(models.Model):# IMPORT FROM MYSQL code = models.CharField(max_length=3, primary_key=True) name = models.CharField(max_length=250) region_id = models.IntegerField(db_column="RegionId") class Meta: managed = False db_table = 'client' And this is the one managed by Django on the other DB: class ClientJuno(models.Model): LABORATORIES = (('SCR','SCREENS'), ('DVR','DVMR'),) client = models.ForeignKey(Client, on_delete=models.SET_NULL, null=True) profiles = models.ManyToManyField(JunoProfile) laboratory = models.CharField(max_length=20, choices=LABORATORIES) See error on opening this last model. Can't find table Client. OperationalError at /admin/settings/clientjules/ no such table: client Request Method: GET Request URL: http://127.0.0.1:8000/admin/settings/clientjules/ Django Version: 2.2.11 Exception Type: OperationalError Exception Value: no such table: client Exception Location: /usr/local/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py in execute, line 383 Python Executable: /usr/local/bin/python Python Version: 3.6.10 Python Path: ['/app/mmike', '/usr/local/lib/python36.zip', '/usr/local/lib/python3.6', '/usr/local/lib/python3.6/lib-dynload', '/usr/local/lib/python3.6/site-packages'] Server time: Mon, 20 Apr 2020 08:11:26 +0000 enter image description here -
passing dictionary value from python to sql stored pocedure
is it possible to pass a dictionary like section value 1 10 2 3 or list section1 [10.2,3,4,5], section2 [1,a,10,"friend"] from python to stored procedure of sql-server. I connected to sql server using pyodbc, from django.db import connection In the stored procedure i need to write xml object based on this parameter. I could have created the table but i dont want to do many operation from python to sql server. How do i do it? -
How to change fields for entire queryset?
I am saving text files with data in the models for moving it from one environment to another. This is one of my models: class MyModel(models.Model): field_1 = models.ForeignKey(Table_1, related_name='some_name') field_2 = models.ForeignKey(Table_2, related_name='other_name') For this model I want to save the data with unique_id instead of id in field_1 and field_2. How can I achieve this for my entire queryset? I tried using .values('field_1__unique_id', 'field_2__unique_id'), but since I am using iterator while saving the data, it threw an error: AttributeError: 'dict' object has no attribute '_meta' in this export function: def export_data(queryset_iterator): first_object = next(queryset_iterator) for field in first_object._meta.get_fields(): # remaining function What am I doing wrong, and what changes should I do on my queryset before giving it to iterator, and without changing export_data function?