У меня есть базовое представление класса, которое я хочу автоматически загрузить в CSV-файл, но, похоже, не знаю, что я делаю. вот код
Model.py
class Pv(models.Model):
accounts =(
('Sub CF','Sub CF'),
('Special','Special'),
('Directors','Directors'),
('Operations','Operations'),
('LSGDP','LSGDP'),
('DWAP','DWAP'),
('Capacity(USD)','Capacity(USD)')
)
acc =(
('Yes','Yes'),
('No', 'No')
)
source =(
('GOG','GOG'),
('Others', 'Others')
)
pv =(
('General','General'),
('Honorarium','Honorarium')
)
center=(
('Cost Center 1','Cost Center 1'),
('Cost Center 2','Cost Center 2'),
('Cost Center 3','Cost Center 3'),
('Cost Center 4','Cost Center 4'),
('Cost Center 5','Cost Center 5')
)
stat =(
('Completed','Completed'),
('Returned','Returned'),
('Cancelled','Cancelled')
)
IA_System_Code = models.AutoField(primary_key = True)
IA_code = models.CharField(max_length = 150)
Date_recieved = models.DateField()
Pv_reference = models.CharField(unique = True, max_length = 120)
Source_of_Funding = models.CharField(max_length=50, choices = source)
Cost_center = models.CharField(max_length=50, choices = center)
Payee = models.CharField(max_length=500)
Description = models.CharField(max_length = 500)
Account_code = models.CharField(max_length=350)
Gross_amount = models.DecimalField(max_digits=19, decimal_places=2)
Withholding_tax = models.DecimalField(max_digits=19, decimal_places=2)
Net_amount = models.DecimalField(max_digits=19, decimal_places=2)
Status = models.CharField(max_length = 60, choices = stat )
Remarks =models.CharField(max_length = 500, blank = True)
Acc_Impress = models.CharField(max_length = 350,choices=acc)
Date_returned =models.DateField(null=True,blank = True)
Type_of_accounts= models.CharField(max_length = 100, choices = accounts)
Type_of_pv = models.CharField(max_length = 20, choices = pv)
returned_to_chest = models.DecimalField(max_digits=19, decimal_places=2)
created = models.DateTimeField(null=True)
created_by = models.ForeignKey('auth.User', blank=True,\null=True,\
default=None,on_delete=models.CASCADE,\
related_name='create')
modified = models.DateTimeField(null=True)
modified_by = models.ForeignKey('auth.User', blank=True,null=True,\
default=None ,on_delete=models.CASCADE,\
related_name='modified')
class Meta():
ordering = ["IA_System_Code"]
def __str__(self):
return self.Description
def save(self, *args, **kwargs):
user = get_current_user()
if user and not user.pk:
user = None
if not self.pk:
self.created_by = user
self.created = datetime.now()
else:
self.modified_by = user
self.modified = datetime.now()
super(Pv, self).save(*args, **kwargs)
view.py
class ReportView(ListView):
model = Pv # model been used
template_name = 'pv/report.html'
context_object_name = 'all_search_results'
def get_queryset(self):
result = super(ReportView, self).get_queryset()
query = self.request.GET.get('search') # get the search critirial from the template
today = datetime.datetime.now()
if query:
if query == "Withholding":
postresult = Pv.objects.filter(Withholding_tax__gt\
=0.00,Date_recieved__year=today.year)
elif query =="Non-Withholding":
postresult = Pv.objects.filter(Withholding_tax__lte\
=0.00, Date_recieved__year=today.year)
elif query =="Accountable-Impress":
postresult = Pv.objects.filter(Acc_Impress__exact\
='Yes',Date_recieved__year=today.year)
elif query =="Non-Accountable-Impress":
postresult = Pv.objects.filter(Acc_Impress__exact\
= 'No',Date_recieved__year=today.year)
else:
postresult = Pv.objects.all()
result = postresult
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename="report.csv"'
today = datetime.datetime.now()
data = result
pvlist =data.filter(Date_recieved__year=today.year)\
.order_by('IA_System_Code')
writer = csv.writer(response)
writer.writerow(['IA_System_Code','IA_code',\
'Date_recieved','Pv_reference',\
'Source_of_Funding','Cost_center','Payee',\
'Description','Account_code',\
'Gross_amount','Withholding_tax',\
'Net_amount','Status','Acc_Impress',\
'Date_returned','Type_of_accounts','Type_of_pv'])
for pv in pvlist :
writer.writerow([pv.IA_System_Code,pv.IA_code,pv.Date_recieved,\
pv.Pv_reference,pv.Source_of_Funding,\
pv.Cost_center, pv.Payee,pv.Description,\
pv.Account_code,pv.Gross_amount,
pv.Withholding_tax,pv.Net_amount,\
pv.Status,pv.Acc_Impress,\
pv.Date_returned,pv.Type_of_accounts,\
pv.Type_of_pv])
else:
result = None
return result
выглядит так, как будто я не знаю что я делаю очевидно, мой код неверен. может кто-нибудь здесь меня. то, чего я хочу достичь - это момент, когда человек заканчивает фильтрацию sh, файл csv должен генерироваться автоматически.
Отредактировано вот мой новый код
view.py
this is my coded my new code.
class ReportView(ListView):
model = Pv # model been used
template_name = 'pv/report.html'
context_object_name = 'all_search_results'
def get_queryset(self):
result = super(ReportView, self).get_queryset()
query = self.request.GET.get('search')
today = datetime.datetime.now()
if query:
if query == "Withholding":
postresult = Pv.objects.filter(Withholding_tax__gt\
=0.00,Date_recieved__year=today.year)
elif query =="Non-Withholding":
postresult = Pv.objects.filter(Withholding_tax__lte =0.00,\
Date_recieved__year=today.year)
elif query =="Accountable-Impress":
postresult = Pv.objects.filter(Acc_Impress__exact\
='Yes',Date_recieved__year=today.year)
elif query =="Non-Accountable-Impress":
postresult = Pv.objects.filter(Acc_Impress__exact =\
'No',Date_recieved__year=today.year)
else:
postresult = Pv.objects.all()
result = postresult
else:
result = None
return result
def get(self, request, *args, **kwargs):
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename="report.csv"'
writer = csv.writer(response)
writer.writerow(['IA_System_Code','IA_code',\
'Date_recieved','Pv_reference',
'Source_of_Funding','Cost_center','Payee',\
'Description','Account_code',\
'Gross_amount','Withholding_tax',\
'Net_amount','Status','Acc_Impress',\
'Date_returned','Type_of_accounts',\
'Type_of_pv','returned_to_chest'])
pvs = self.get_queryset()
for pv in pvs:
writer.writerow([pv.IA_System_Code,pv.IA_code,\
pv.Date_recieved,pv.Pv_reference,\
pv.Source_of_Funding,pv.Cost_center,\
pv.Payee,pv.Description,pv.Account_code,\
pv.Gross_amount,pv.Withholding_tax,\
pv.Net_amount,pv.Status,pv.Acc_Impress,\
pv.Date_returned,pv.Type_of_accounts,\
pv.Type_of_pv,pv.returned_to_chest])
return response
отредактированная версия кода работает, но она даже не открывает шаблон для фильтрации, вы просто запускаете функцию get. Есть ли способ, которым код может позволить вам фильтровать, прежде чем он запустит функцию get. Кажется, я не знаю, что делаю. любая помощь сделает спасибо