Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How does djagno update urls when you add a model to an app?
If I have an app (blog) and I create a posts model and then add a schedule model how are the urls for schedule created? Are they imported with the blog.urls like the posts in 3 line below? urlpatterns = [ path('admin/', admin.site.urls), path('', include('app.urls')), path('accounts/', include('django.contrib.auth.urls')) ] Then how would django reference the schedule model views? Is it path('schedule/,views.scheduleDetail.as_view(),name='sidebar.html') in the myblog.urls? Thanks -
How do I fix the codsad dsdsd sd?
Bang Bang Chief Keef Glo GAng Bang Bang Chief Keef Glo GAng Bang Bang Chief Keef Glo GAng Bang Bang Chief Keef Glo GAng Bang Bang Chief Keef Glo GAng Bang Bang Chief Keef Glo GAng Bang Bang Chief Keef Glo GAng Bang Bang Chief Keef Glo GAng Bang Bang Chief Keef Glo GAng Bang Bang Chief Keef Glo GAng Bang Bang Chief Keef Glo GAng Bang Bang Chief Keef Glo GAng Bang Bang Chief Keef Glo GAng Bang Bang Chief Keef Glo GAng Bang Bang Chief Keef Glo GAng Bang Bang Chief Keef Glo GAng Bang Bang Chief Keef Glo GAng Bang Bang Chief Keef Glo GAng Bang Bang Chief Keef Glo GAng Bang Bang Chief Keef Glo GAng Bang Bang Chief Keef Glo GAng Bang Bang Chief Keef Glo GAng Bang Bang Chief Keef Glo GAng Bang Bang Chief Keef Glo GAng import pyvisa import time import pandas as pd from colorama import Fore, Style import sys rm = pyvisa.ResourceManager() rm.list_resources() ps1 = rm.open_resource('GPIB0::8::INSTR') ps2 = rm.open_resource('GPIB0::7::INSTR') def PowerOFF(): ps1.write("OUTP:STAT OFF") ps2.write("OUTP:STAT OFF") def PowerON(): ps1.write("VOLT 15.0") ps1.write("OUTP:STAT ON") ps2.write("INST P25V") ps2.write("VOLT 15.0") ps2.write("OUTP:STAT ON") temp = input("on or off:\n") if temp =="on": b1 = [] b2 = … -
column "value" is of type smallint but expression is of type timestamp with time zone LINE 1: ... '2022-06-16T23:17:27.223553+00:00'
_Hi! I want to add time like "00:00". class Time(models.Model): day = models.DateTimeField(null=True) value = models.DateTimeField(auto_now_add=True, null=True) def add_time(request, str): if request.method == 'POST': form = TimeForm(request.POST) time = request.POST.get('time') time = Time(id_goal=goal, day=datetime.now(), value=time, description=description) time.save() When i had value = models.TimeField(null=True) it was good and worked before I had deployed to Heroku. After it wrote me: django.db.utils.ProgrammingError: column "value" is of type smallint but expression is of type timestamp with time zone which I didn't understand and now I have a big headache for over two-three days. Haha :P -
Is there a way to create a django model with 20 columns
I am currently building a django application and i want to have a model with 20 columns. Is there a simplest way to do this? Please help. -
Validation Check not working to checkPostive value Django Validation in Form.py
I am working this validation check in django , i have to check postiva values. I have values a,b,c,d if (a,b) also (c,d) positive value will not allowed, i wrote the code this way but do not know why is not checking the validation. I am working on django forms.py for i in range(count): a = int(self.data.get(f'runtime_set-{i}-a') or 0) b = int(self.data.get(f'runtime_set-{i}-b') or 0) c = int(self.data.get(f'runtime_set-{i}-c') or 0) d = int(self.data.get(f'runtime_set-{i}-end_bbch') or 0) if a ==b==c==d: continue if (a + b) > 0 + (c + d) > 0: raise ValidationError( "When A '{a}' , B '{b}' is postive then C '{c}' and d'{d}' positive value is not allowed ") -
How i can get the value string from a drop down list
please how i can get correctly the value from the drop down list, i have used django-widget-tweaks library . this is the code of the field dropdown list that i want to get the value string from it: <p >{{ form.category_column.label_tag }}</p> <p id="category_column_id">{% render_field form.category_column autocomplete="off" hx-get="/sizescolumn/" hx-target="#id_sizes_column" %}</p> I have tried to got the value using javascript by this line of code : var select = document.getElementById('category_column_id').value; ---->but it doesn't work. thanks in advance. -
Django UserCreationForm's fields doesn't show up
class UserRegForm(forms.ModelForm): ...... class Meta: model = get_user_model() # model has: username, email, full_name, is_admin/is_staff/etc. fields = ('username', 'email', 'full_name',) And yet, when going into Django admin and pressing "new user", it asks for username and password only... And, when I create a user like that and try to edit/change it, the 'email' field is completely empty (which is the username_field)... Why? -
How to override model form to create a user in Django
I am trying to create a new user from the modelform by calling the CustomerUserManager in managers.py class CustomUserCreationForm(UserCreationForm): def __init__(self, *args, **kwargs): super(CustomUserCreationForm,self).__init__(*args, **kwargs) try: if args[0]["email"]: self.email= args[0]["email"] self.password= args[0]["password1"] except: pass class Meta: model = CustomUser fields = "__all__" def save(self, **kwargs): return CustomUserManager.create_user(self,email=self.email,password=self.password,name="hic") The managers.py is class CustomUserManager(BaseUserManager): def create_user(self, email, password, name,**extra_fields): ... user = self.model(email=email,name=name, stripe_customer_id=customer.id ,**extra_fields) user.set_password(password) user.save() return user Obviously the self.model does not exist, so how can I correctly create that user from the modelform? If I import the model, I get circular error import. here is my model.py class CustomUser(AbstractUser): username = None email = models.EmailField(_('email address'), unique=True) name = models.CharField(verbose_name=_("first name"), max_length=50) stripe_customer_id = models.CharField(max_length=120) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['name'] objects = CustomUserManager() -
'CustomUserForm' object has no attribute 'save_m2m' when creating custom user
I am trying to create a user using the following code: class CustomUserCreationForm(UserCreationForm): def __init__(self, *args, **kwargs): super(CustomUserCreationForm,self).__init__(*args, **kwargs) try: if args[0]["email"]: self.email= args[0]["email"] self.password= args[0]["password1"] except: pass class Meta: model = CustomUser fields = "__all__" def save(self, commit=False,**kwargs): customer = stripe.Customer.create( email=self.email, name="test", ) user = CustomUser.objects.create(email=self.email,password=self.password) user.set_password(self.password) user.save_m2m() return user I get the error 'CustomUser' object has no attribute 'save_m2m' Can someone please assist on how to solve this? -
Django Import Export data witjout ID
I tried to export data from Django to Excel, but every thing walk behind me, when I export a Excel File, Django Export only Ids : enter image description here I tried to walk behind some tutorials like : https://django-import-export.readthedocs.io/en/latest/api_widgets.html and Django call 'id' expected a number but got string. In Django App, I have: models.py from pyexpat import model from statistics import mode from django.db import models from django.contrib.auth.models import User from django.db.models.base import Model from django.forms import IntegerField class Post(models.Model): name = models.CharField(max_length=150) def __str__(self): return str(self.name) class Person(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) name = models.CharField(max_length=100) def __str__(self): return f"({self.name} is {self.post} " class Room(models.Model): name = models.CharField(max_length= 150 ) def __str__(self): return str(self.name) class Classification(models.Model): name = models.ForeignKey(Person, on_delete=models.CASCADE) room = models.ForeignKey(Room, on_delete=models.CASCADE) date = models.DateField(auto_created=False) def __str__(self): return f"({self.name} Take {self.room} at {self.date})" admin.py from django.contrib import admin from import_export.admin import ImportExportModelAdmin from .models import * from import_export import fields, resources from import_export.widgets import ForeignKeyWidget @admin.register(Post, Room, Classification, Person) class TestappImportExport(ImportExportModelAdmin): pass class Classificationresource(resources.ModelResource): name = fields.Field( column_name='name', attribute='name', widget=ForeignKeyWidget(Person, 'name')) room = fields.Field( column_name = 'room', attribute = 'room', widget= ForeignKeyWidget(Room, 'name')) class Meta: fields = ('name', 'room') even I tried to reverse class Classificationresource(resources.ModelResource) … -
How to loop through particular element in the payload or JSON
I trying to insert all the fields from the payload where values of QId and Answer changes. All I did is I tried looping the QId and Answer but the only one last data is getting inserted. I wanted to insert all value of the QId and Answer views.py cursor = connection.cursor() for ran in request.data: print('request.data--', ran) auditorid =ran.get('AuditorId') print('SaveUserResponse auditorid---', auditorid) ticketid = ran.get('TicketId') qid = ran.get('QId') answer = ran.get('Answer') sid = '0' print('sid--', sid) for i in request.data: qid = i['QId'] print('qid--', qid) answer = i['Answer'] print('answer--', answer) cursor.execute('EXEC [dbo].[sp_SaveAuditResponse] @auditorid=%s,@ticketid=%s,@qid=%s,@answer=%s,@sid=%s', (auditorid,ticketid,qid,answer, sid)) print(qid) result_st = cursor.fetchall() print('sp_SaveAuditResponse', result_st) for row in result_st: print('sp_SaveAuditResponse', row) return Response(row[0]) payload: [{"AuditorId":130,"Agents":"","Supervisor":"","TicketId":"325423432","QId":42,"Answer":"2","SID":"0","Comments":""}, {"AuditorId":130,"Agents":"","Supervisor":"","TicketId":"325423432","QId":43,"Answer":"2","SID":"0","Comments":""}, {"AuditorId":130,"Agents":"","Supervisor":"","TicketId":"325423432","QId":44,"Answer":"2","SID":"0","Comments":""}, {"AuditorId":130,"Agents":"","Supervisor":"","TicketId":"325423432","QId":45,"Answer":"2","SID":"0","Comments":""}, {"AuditorId":130,"Agents":"","Supervisor":"","TicketId":"325423432","QId":46,"Answer":"3","SID":"0","Comments":""}, {"AuditorId":130,"Agents":"","Supervisor":"","TicketId":"325423432","QId":47,"Answer":"5","SID":"0","Comments":""}, {"AuditorId":130,"Agents":"","Supervisor":"","TicketId":"325423432","QId":48,"Answer":"5","SID":"0","Comments":""}, {"AuditorId":130,"Agents":"","Supervisor":"","TicketId":"325423432","QId":49,"Answer":"2","SID":"0","Comments":""}, {"AuditorId":130,"Agents":"","Supervisor":"","TicketId":"325423432","QId":50,"Answer":"5","SID":"0","Comments":""}] -
Is there a way to configure Apache to auto-recognize URLs for Django vs React without hard-coding each endpoint?
We're using Apache 2.4 with React 17 and a Django 3.2 (Python 3.9) application. Curious about a better way to set up our Apache configs to route requests to the React and Django apps. Right now, our Apache virtual hosts file hard-codes which routes need to be handled by the React app vs which need to be handled by Django ... AliasMatch ^/(?!people)(?!states/)(?!countries/)(?!predefined_types/)(?!coop_types/)(?!coops/)(?!data)(?!save_to_sheet_from_form).* /var/www/html/client/build/$0 <Directory "/var/www/html/client/build/"> Options Indexes FollowSymLinks AllowOverride all </Directory> WSGIDaemonProcess ssl_directory home=/var/www/html/web python-home=/var/www/html/web/venv WSGIProcessGroup ssl_directory WSGIScriptAlias /coops /var/www/html/web/directory/wsgi.py/coops process-group=ssl_directory WSGIScriptAlias /data /var/www/html/web/directory/wsgi.py/data process-group=ssl_directory WSGIScriptAlias /countries /var/www/html/web/directory/wsgi.py/countries process-group=ssl_directory WSGIScriptAlias /states /var/www/html/web/directory/wsgi.py/states process-group=ssl_directory WSGIScriptAlias /predefined_types /var/www/html/web/directory/wsgi.py/predefined_types process-group=ssl_directory WSGIScriptAlias /coop_types /var/www/html/web/directory/wsgi.py/coop_types process-group=ssl_directory WSGIScriptAlias /people /var/www/html/web/directory/wsgi.py/people process-group=ssl_directory WSGIScriptAlias /save_to_sheet_from_form /var/www/html/web/directory/wsgi.py/save_to_sheet_from_form process-group=ssl_directory The Django app, for its part, defines urls in the standard way (in our urls.py file) ... ... urlpatterns = [ path('data', views.data, name='data'), path('coops/no_coords', views.coops_wo_coordinates, name='coops_wo_coordinates'), path('coops/unapproved', views.unapproved_coops, name='unapproved_coops'), path('coops/', views.CoopList.as_view()), path('coops/<int:pk>/', views.CoopDetail.as_view()), path('people/', views.PersonList.as_view()), path('people/<int:pk>/', views.PersonDetail.as_view()), path('users/', views.CreateUserView.as_view()), path('predefined_types/', views.CoopTypeList.as_view()), path('coop_types/', views.CoopTypeList.as_view()), path('countries/', views.CountryList.as_view()), path('states/<country_code>', views.StateList.as_view()), path('login', views.signin), path(settings.LOGOUT_PATH, views.signout), path('user_info', views.user_info), ] urlpatterns = format_suffix_patterns(urlpatterns) Is there a more automated way we can get Apache to know what routes shoudl go to Django vs React? Whenever we add a new Django endpoint, we have to add a … -
Benefits of using SmallAutoField as primary key in Django?
My table will have around 2000 rows. Are there any performance benefits to using SmallAutoField as the primary key rather than the standard AutoField? Also, if in the future I run out of the 32,000 incrementing integers in my SmallAutoField, how difficult would it be to change it to a regular AutoField? PS. I am using SQLite but may switch to Postgres. -
How to collect an image file and save it in database
This is a project that collects inputs for name, price and image. The major problem I am encountering is posting an image from my frontend(html) to the backend(database). These are my codes, what is the issue models.py from django.db import models from datetime import datetime class Product(models.Model): name = models.CharField(max_length=250) price = models.FloatField(default=0) image = models.ImageField() forms.py from django import forms class ProductCreationForm(forms.Form): name = forms.CharField(label="Product Name", max_length=250, required=True) price = forms.DecimalField(label="Price", required=True, initial=0) image = forms.ImageField(label="Image", required=True, widget=forms.FileInput(attrs={'accept': "image/x-png, image/jpeg"})) views.py def product_create(request): form = ProductCreationForm() if request.method == "POST": form = ProductCreationForm(request.POST) if form.is_valid(): name = form.cleaned_data["name"] price = form.cleaned_data["price"] image = form.cleaned_data["image"] new_item = Product.objects.create(name=name, price=price, image=image) new_item.save() return redirect('shelf') else: return render(request, "workbench/product_create.html", {"form": form}) create.html <form action="", method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit" >submit</button> </form> urls.py from django.urls import path from . import views urlpatterns = [ path('', views.shelf, name="shelf"), path('/create', views.product_create, name="product-create"), ] -
I can I get Countries Flags in django-phonenumber-field
I have used django-phonenumber-field in my project with Babel which is working fine with drop down of all countries with their international dialing code. My problem is that I want each country flag attached to their dialing codes without their names so that the phonenumber drop down field will be smaller. Attached is what I presently have. This is example of what I want to achieve with django-phonenumber-field. And you can observe that my phone number fields are two; one has the international code and the other field is where the phone number is to be entered whereas I want all in one field with Countries Flags flags and international codes without their names so that all can in one row field. Anticipating your prompt answer, thanks. -
Integrating React Build file inside Django project
I have been building web apps using NextJS and Django for some time. But recently, my boss gave me the requirements for using ReactJS and using the build files inside Django as templates. Now, I have never tried it before, but according to this Tutorial, it is possible. But my question is, should I do it? Would I face any performance issues in the future if I do this? Or will there be any bugs or issues related to routing? I know I can try it myself, but I am looking for some expert advice from senior developers. -
How Do I Get The Events In Between Start and End Time To Display On My Calendar
I'm using a tutorial I found online...and it's mostly working...I'm stuck when I'm trying to loop through the list of events and show them on a daily basis. If I have an event that starts on June 1 and ends on June 5th...I'd like to be able to show the event on June 2 on my list and June 3 and June 4. Currently I can only get it to say it starts on June 1 and ends on June 5. I've tried multiple different filters utilizing GTE and LTE and that doesn't seem to help. Here's my Calendar utility... class Calendar(HTMLCalendar): def __init__(self, year=None, month=None, dropdown=None): self.dropdown = dropdown self.year = year self.month = month super(Calendar, self).__init__() # formats a day as a td # filter events by day def formatday(self, day, events): events_per_day = events.filter(start_time__day__lte=day, end_time__day__gte=day) d = '' for event in events_per_day: d += f'<li> {event.get_html_url} </li>' if day != 0: return f"<td><span class='date'>{day}</span><ul> {d} </ul></td>" return '<td></td>' # formats a week as a tr def formatweek(self, theweek, events): week = '' for d, weekday in theweek: week += self.formatday(d, events) return f'<tr> {week} </tr>' # formats a month as a table # filter events by year … -
Django dynamic mass email sending like an abandoned cart email
I'm trying to run an auto match feature with filters.. Which is easy. I just have to filter by the users criteria. Like for example I want to only get notifications on blog posts about sports and football... Another user might want to be notified on movies and series only. I've managed to get a working logic for this already... Now my challenge currently is sending out mass emails to these users.. The small should contain a list of all the their beloved user special posts.. Same as how abandoned carts works which sends an email along with the user special cart items.. I dont want to bother about celery for now il have ba send mail button that would do the sending for me manually... But I need help with the logic.. So each user gets their user specific content.. -
Forbidden (CSRF token missing.) - but I have used the csrf_exempt decorator?
I am working on a small app for an online course, in which a fetch request is required. Since Django requires a csrf token by default, I have used the csrf_exempt decorator on a few of my view functions to bypass this requirement(I know this is not secure, but its currently not necessary to add such verification). However, on one particular route, I have noticed that I keep getting a 403 status code, with the reason "Forbidden (CSRF token missing.)" This is even after adding the csrf_exempt decorator to the view function. What is the reason behind this? My view function and fetch request are below: @csrf_exempt def follow_unfollow(request): # the rest of my function here... fetch("/following", { method: "PUT", body: JSON.stringify({ action: "follow", followee: user, }) }) .then(response => { if (response.status === 400) { location.reload; } else if (response.status === 401) { alert("You must be logged in to follow/unfollow a user!"); window.location = "/login"; } else { return response.json(); } }) .then(data => { // data processing on client-side }) -
Quick question: CSS alteration for DMs on social media site
I am trying to get the image to line up above the sent message as you would have it in most standard DMs: https://prnt.sc/IR__3qyiXqlI (what I want it to look like) But for some reason, the text attached to the image proceeds to layer itself beside the image rather than below the image, as shown in the screenshot below. When I add float: right; to my CSS the image and the text layer horizontally in a strange manner: what it looks like currently Ideally, the image should be on the same side as the texts from the person who sent the image and should be just above the message that was attached to the image (as is commonplace). The HTML doc the DMs are stored on: thread.html: > {% extends 'landing/base.html' %} {% load crispy_forms_tags %} > > {% block content %} > > <div class="container"> > <div class="row"> > <div class="card col-md-12 mt-5 p-3 shadow-sm"> > {% if thread.receiver == request.user %} > <h5><a href="{% url 'profile' thread.user.profile.pk %}"><img class="rounded-circle post-img" height="50" width="50" > src="{{ thread.user.profile.picture.url }}" /></a> @{{ thread.user > }}</h5> > {% else %} > <h5>@{{ thread.receiver }}</h5> > {% endif %} > </div> > </div> > … -
How to call the browser payload
I'm trying to loop through the browser payload by request.data but after executing the first set of dictionary it start to execute the keys rather than next dictionary which causing an error 'str' object has no attribute 'get' . Is this the way to call the payload dictionary through request.data. How could I achieve this without any error. I don't have any error or issue in the payload views.py: def SaveUserResponses(request): cursor = connection.cursor() for ran in request.data: print('request.data--', ran) auditorid =ran.get('AuditorId') print('SaveUserResponse auditorid---', auditorid) ticketid = ran.get('TicketId') qid = ran.get('QId') answer = ran.get('Answer') sid = '0' print('sid--', sid) print('qid--', qid) cursor.execute('EXEC [dbo].[sp_SaveAuditResponse] @auditorid=%s,@ticketid=%s,@qid=%s,@answer=%s,@sid=%s', (auditorid,ticketid,qid,answer, sid)) result_st = cursor.fetchall() print('sp_SaveAuditResponse', result_st) for row in result_st: print('sp_SaveAuditResponse', row) return Response(row[0]) return Response(sid) when I print request.data its just returning only the keys ran ran--- AuditorId ran--- AuditorId ran--- AuditorId ran--- AuditorId ran--- AuditorId ran--- AuditorId ran--- AuditorId ran--- AuditorId ran--- AuditorId rather than calling the dictionary here is the browser payload: [{"AuditorId":130,"Agents":"","Supervisor":"","TicketId":"325423432","QId":42,"Answer":"2","SID":"0","Comments":""}, {"AuditorId":130,"Agents":"","Supervisor":"","TicketId":"325423432","QId":43,"Answer":"2","SID":"0","Comments":""}, {"AuditorId":130,"Agents":"","Supervisor":"","TicketId":"325423432","QId":44,"Answer":"2","SID":"0","Comments":""}, {"AuditorId":130,"Agents":"","Supervisor":"","TicketId":"325423432","QId":45,"Answer":"2","SID":"0","Comments":""}, {"AuditorId":130,"Agents":"","Supervisor":"","TicketId":"325423432","QId":46,"Answer":"3","SID":"0","Comments":""}, {"AuditorId":130,"Agents":"","Supervisor":"","TicketId":"325423432","QId":47,"Answer":"5","SID":"0","Comments":""}, {"AuditorId":130,"Agents":"","Supervisor":"","TicketId":"325423432","QId":48,"Answer":"5","SID":"0","Comments":""}, {"AuditorId":130,"Agents":"","Supervisor":"","TicketId":"325423432","QId":49,"Answer":"2","SID":"0","Comments":""}, {"AuditorId":130,"Agents":"","Supervisor":"","TicketId":"325423432","QId":50,"Answer":"5","SID":"0","Comments":""}] -
Django rest framework serializer.instance is not able to be saved
I have retrieved the object by doing the following and I am trying to update a field in the object. However, it is throwing an exception "response object has no attribute save" def retrieve(self, request, token=None): object_serializer = self.serializer_class(self.get_object(token=token)) obj = object_serializer.instance obj.update_field = "test field" obj.save() return Response(object_serializer.data) -
django : How can I display the list of images of an album?
I create an album model, and an Image model, one album can have lot of image. How can I do to display in the JSON response (of album) the list of images containing in the album ? this is my models : class Album(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=30) def __str__(self): return self.title class AlbumImage(models.Model): image = models.ImageField(blank=True, null=True, upload_to=upload_path_image) title = models.CharField(max_length=30) album = models.ForeignKey(Album, on_delete=models.CASCADE) def __str__(self): return self.title -
Django Query is being called every time the variable attributed to it is called
I have this code: players = room.player_set.all().order_by('?') # mix the players The 'order_by' is to get a random order of elements, which is needed for this case, and not expensive to the database since there is at most 3 elements in the player_set. Every time the variable 'players' is called the query is made... meaning, every time the variable is called (for example, in print) the value of 'players' changes as well... I've tried deepcopy with no success. -
django - StreamingHttpResponse export csv with fields name
I have created a view to export from the database to a csv file, the code works fine, but the exported csv file does not have the field names, how can I add them? i am using values_list because the performance is higher I am using this code: CSVStream.py: class CSVBuffer: """An object that implements just the write method of the file-like interface. """ def write(self, value): """Return the string to write.""" return value class CSVStream: """Class to stream (download) an iterator to a CSV file.""" def export(self, filename, iterator): # 1. Create our writer object with the pseudo buffer writer = csv.writer(CSVBuffer()) # 2. Create the StreamingHttpResponse using our iterator as streaming content response = StreamingHttpResponse((writer.writerow(data) for data in iterator), content_type="text/csv") # 3. Add additional headers to the response response['Content-Disposition'] = f"attachment; filename={filename}.csv" # 4. Return the response return response views.py class descargarAsignacion(View): template_name='gestionAsignacion/detalle_Asignacion.html' def get(self, request,pk): # 1. Get the iterator of the QuerySet queryset=AsignacionSurtigas.objects.filter(idasignacion=pk) queryset_valueslist=queryset.values_list( "id", "idasignacion", "producto", "contrato", "nombre_suscriptor", "tipo_servicio", "total_deuda", "corriente_no_vencida_actual", "corrente_vencida", "total_deuda_corriente", "cuota_minima_agente", "politica_surtigas", "categoria", "estrato", "ref_anio", "historico_ref", "ciclo", "medidor", "lectura", "plan_acuerdo", "descripcion_barrio", "direccion", "dias_deuda", named=True, ) # 2. Create the instance of our CSVStream class csv_stream = CSVStream() # 3. Stream (download) the …