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

#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
 
#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), 
]  
#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"
//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