Reputation: 31
In my app I've created a working function to dowload all the user information in my database. In my html page I'd like also to add the date of the latest time that the csv file was downloaded and how many new profile where added since the last download. I've thought to use the iformation stored in the name file to do so but I'm getting this error name 'file_name' is not defined
account.views
@login_required
def download_csv(request):
response = HttpResponse(content_type='text/csv')
profile_total = Information.objects.all().count()
profile_csv_date_donwload = str(datetime.today().strftime("%d-%m-%Y"))
file_naname = + profile_csv_date_donwload + str(profile_total) +'.csv'
response['Content-Disposition'] = 'attachment; filename=' + file_naname
writer = csv.writer(response, delimiter=';')
info = Information.objects.all()
writer.writerow(['first_name', 'last_name', 'gender', 'birthdate'])
for i in info:
writer.writerow([i.first_name, i.last_name, i.gender, i.birthdate])
return response
donwload.views
from account.views import download_csv
def download_page(request):
profile_total = Information.objects.all().count()
latest_d_csv = file_name[0:10]
latest_n_csv = file_name[11:]
new_profile = profile_total - int(latest_n_csv)
context = {
'profile_total': profile_total,
'latest_d_csv': latest_d_csv
'latest_n_csv': latest_n_csv
'new_profile': new_profile
}
return render(request, 'page/download.html', context)
html
<div class="col-md-8">
<div class="row gutters-sm">
<div class="col-sm-6 mb-3">
<div class="card h-100">
<div class="card-body">
<h6 class="d-flex align-items-center mb-3">Profile CSV</h6>
<br/>
<small>Profile in Database: {{ profile_total }}</small>
<br/>
<small>Latest Download: {{ latest_d_csv}}</small>
<br/>
<small>New Profile: {{ new_profile }}</small>
</div>
</div>
</div>
Upvotes: 0
Views: 89
Reputation: 531
File_name in download_page is not defined, so either to call this function from download_cv where file_name is defined and passing file name as an argument, or passe it via redirect download_cv to download_page..
Check if there is typo error in below line( its file_naname instead of file_name) file_naname = + profile_csv_date_donwload + str(profile_total) +'.csv
How to pass argument to view function:
1-passing argument from function to function (both function take request as an argument):
in url.py:
urlpatterns = [
path('lowad_page/<str:file_name>', view.downlowad_page, name='downlowad_page'),
]
in view.py
def download_csv(request):
.
.
.
return redirect('downlowad_page', file_name)
def download_page(request, file_name):
.
.
.
return response(request, ......)
2-In html you can pass the argument by using url tag:
"{% url 'downlowad_page' file_name %}"
make sure file name is passed to html (you can pass it via context)
Upvotes: 1