I have a model called leads and am trying to export a single lead from my database. Currently I am only able to export all of the leads.
Model.py
class Lead(models.Model):
transfer_date=models.DateField(blank=True, null=True)
callback_date = models.DateField(blank=True, null=True)
contact_date = models.DateField(blank=True, null=True)
first_name = models.CharField(max_length=20)
last_name = models.CharField(max_length=20)
address = models.CharField(default=0, max_length=50)
city = models.CharField(max_length=30, default="")
state = models.CharField(max_length=20, default="")
zipcode = models.IntegerField(default=0)
phone = models.CharField(max_length=10, null=True, default="", blank=True)
cell = models.CharField(max_length=10, null=True, default="", blank=True)
email = models.EmailField(default="")
def __str__(self):
return f"{self.first_name} {self.last_name}"
Views.py
def export(request):
response = HttpResponse(content_type='text/csv')
writer = csv.writer(response)
writer.writerow(['First Name', 'Last Name', 'Email'])
for lead in Lead.objects.all().values_list('first_name', 'last_name', 'email'):
writer.writerow(lead)
response['Content-Disposition'] = 'attachment; filename="Lead.csv"'
return response
CodePudding user response:
Let's assume a separate view for this:
def export_single_lead(request):
response = HttpResponse(content_type='text/csv')
writer = csv.writer(response)
writer.writerow(['First Name', 'Last Name', 'Email'])
lead = Lead.objects.last() # Or get the lead you want some other way
writer.writerow((lead.first_name, lead.last_name, lead.email))
response['Content-Disposition'] = 'attachment; filename="Lead.csv"'
return response
CodePudding user response:
def export(request, pk):
response = HttpResponse(content_type='text/csv')
writer = csv.writer(response)
writer.writerow(['First Name', 'Last Name', 'Email'])
lead = Lead.objects.get(id=pk)
writer.writerow((lead.first_name, lead.last_name, lead.email))
response['Content-Disposition'] = 'attachment; filename="Lead.csv"'
return response