article

Thursday, April 16, 2020

Django How to Export Data to CSV File


Django How to Export Data to CSV File

Export Data to CSV File No need to install dependencies. Use it if you do not need any fancy formating.

import csv

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#views.py
from django.shortcuts import render 
from django.http import HttpResponse
from django.contrib.auth.models import User
import csv
from myapp.models import StudentForm #models.py
 
def index(request):  
    return render(request,"index.html"
  
def export_users_csv(request):
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename="users.csv"'
  
    writer = csv.writer(response)
    writer.writerow(['Username', 'First name', 'Last name', 'Email address'])
  
    users = User.objects.all().values_list('username', 'first_name', 'last_name', 'email')
    for user in users:
        writer.writerow(user)
 
    return response
 
def export_student_csv(request):
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename="student.csv"'
  
    writer = csv.writer(response)
    writer.writerow(['First name', 'Last name', 'Email address'])
  
    student = StudentForm.objects.all().values_list('firstname', 'lastname', 'email')
    for student_rs in student:
        writer.writerow(student_rs)
 
    return response
1
2
3
4
5
6
7
8
9
10
11
#urls.py
from django.contrib import admin 
from django.urls import path 
from myapp import views 
 
urlpatterns =
    path('admin/', admin.site.urls), 
    path('index/', views.index),
    path('export_users_csv/', views.export_users_csv),
    path('export_student_csv/', views.export_student_csv),
1
2
3
4
5
6
7
8
9
10
11
12
13
#models.py
from django.db import models
  
# Create your models here.
class StudentForm(models.Model): 
    firstname = models.CharField("Enter first name", max_length=50
    lastname  = models.CharField("Enter last name", max_length = 50
    email     = models.EmailField("Enter Email"
    bio       = models.TextField(blank=True
    file      = models.FileField() # for creating file input 
   
    class Meta: 
        db_table = "student"
1
2
3
4
5
6
7
8
9
10
11
12
13
//templates/index.html
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>Django How to Export Data to CSV File</title>
  </head>
  <body>
  <p><h2>Django How to Export Data to CSV File</h2></p>
 <p><h4><a href="/export_users_csv">Export all users</a></h4></p>
<p><h4><a href="/export_student_csv">Export all Students</a></h4></p>
  </body>
</html>

Related Post