I've got a function which sends an email with expenses. Everything works fine, but I have no idea how to implement a small part of the code into a template and give for the user an option to choose a period of time. For example: user should choose a year and month from the template.
def mail_from_web(request):
email = EmailMessage('Your expenses', 'Hello there. Some text', 'email@from',
['email@to'])
attachment_csv_file = StringIO()
writer = csv.writer(attachment_csv_file, delimiter=',')
writer.writerow(['Date', 'Customer', 'Car park'])
for call in Call.objects.filter(date__year='2019', date__month='04').order_by('date'):
writer.writerow([call.date_start.strftime("%Y-%m-%d"), call.customer, call.expenses])
email.attach('expenses.csv', attachment_csv_file.getvalue(), 'text/csv')
email.send(fail_silently=False)
return render(request, 'calls/mail_sent.html')
Instead of this: objects.filter(date__year='2019', date__month='04')
create a form
class MyForm(forms.Form)
year = forms.IntegerField(
widget = forms.NumberInput(min=2019)
)
month = forms.IntegerField(
widget = forms.NumberInput(min=1, max=12))
Add it to your context to pass to the template.
Show in the template ... {{form}} ...
In the view
year = int(request.POST['year'])
month = int(request.POST['month'])
Change Call.objects.filter(date__year='2019', date__month='04')
to Call.objects.filter(date__year=year, date__month=month)
I've just realised you're not using int for the year and month so you'll need to modify accordingly.