├── dashboard ├── __init__.py ├── wsgi.py ├── urls.py └── settings.py ├── reports ├── __init__.py ├── tests.py ├── apps.py ├── resources.py ├── admin.py ├── models.py └── views.py ├── requirements.txt ├── employees.csv ├── README.md ├── templates ├── export.html ├── import.html └── base.html ├── manage.py └── LICENSE /dashboard/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /reports/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | django 2 | django-import-export 3 | -------------------------------------------------------------------------------- /reports/tests.py: -------------------------------------------------------------------------------- 1 | from django.test import TestCase 2 | 3 | # Create your tests here. 4 | -------------------------------------------------------------------------------- /reports/apps.py: -------------------------------------------------------------------------------- 1 | from django.apps import AppConfig 2 | 3 | 4 | class ReportsConfig(AppConfig): 5 | name = 'reports' 6 | -------------------------------------------------------------------------------- /employees.csv: -------------------------------------------------------------------------------- 1 | first_name,last_name,email,day_started,location,id 2 | Peter,Parker,peter@parker.com,2015-05-18,New York, 3 | James,Bond,james007@bond.com,2014-08-11,London, -------------------------------------------------------------------------------- /reports/resources.py: -------------------------------------------------------------------------------- 1 | from import_export import resources 2 | from .models import Employee 3 | 4 | class EmployeeResource(resources.ModelResource): 5 | class Meta: 6 | model = Employee -------------------------------------------------------------------------------- /reports/admin.py: -------------------------------------------------------------------------------- 1 | from import_export.admin import ImportExportModelAdmin 2 | from django.contrib import admin 3 | from .models import Employee 4 | 5 | @admin.register(Employee) 6 | class EmployeeAdmin(ImportExportModelAdmin): 7 | pass -------------------------------------------------------------------------------- /reports/models.py: -------------------------------------------------------------------------------- 1 | from django.db import models 2 | 3 | class Employee(models.Model): 4 | first_name = models.CharField(max_length=30) 5 | last_name = models.CharField(max_length=60) 6 | email = models.EmailField(blank=True) 7 | day_started = models.DateField() 8 | location = models.CharField(max_length=100, blank=True) 9 | 10 | def __str__(self): 11 | return self.first_name -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Django-Import-Export 2 | Report app using django-import-export package (tutorial) 3 | 4 | ## Getting Started 5 | 6 | This tutorial works on **Python 3+** and Django 2+. 7 | 8 | Install dependencies: 9 | 10 | ``` 11 | python3 -m pip3 install -r requirements.txt 12 | ``` 13 | 14 | and run following commands: 15 | 16 | ``` 17 | python3 manage.py makemigrations reports 18 | python3 manage.py migrate 19 | python3 manage.py runserver 20 | ``` 21 | -------------------------------------------------------------------------------- /dashboard/wsgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | WSGI config for dashboard project. 3 | 4 | It exposes the WSGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/2.2/howto/deployment/wsgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.wsgi import get_wsgi_application 13 | 14 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'dashboard.settings') 15 | 16 | application = get_wsgi_application() 17 | -------------------------------------------------------------------------------- /templates/export.html: -------------------------------------------------------------------------------- 1 | {% extends 'base.html' %} 2 | 3 | {% block content %} 4 |

Export Data

5 |

exporting from database

6 |
7 | {% csrf_token %} 8 |

Please select format of file.

9 | 15 | 16 |
17 | Return Home View 18 | {% endblock %} -------------------------------------------------------------------------------- /templates/import.html: -------------------------------------------------------------------------------- 1 | {% extends 'base.html' %} 2 | 3 | {% block content %} 4 |

Import Data

5 |

importing to database

6 |
7 | {% csrf_token %} 8 | 9 |

Please select format of file.

10 | 15 | 16 |
17 | Return Home View 18 | {% endblock %} -------------------------------------------------------------------------------- /manage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """Django's command-line utility for administrative tasks.""" 3 | import os 4 | import sys 5 | 6 | 7 | def main(): 8 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'dashboard.settings') 9 | try: 10 | from django.core.management import execute_from_command_line 11 | except ImportError as exc: 12 | raise ImportError( 13 | "Couldn't import Django. Are you sure it's installed and " 14 | "available on your PYTHONPATH environment variable? Did you " 15 | "forget to activate a virtual environment?" 16 | ) from exc 17 | execute_from_command_line(sys.argv) 18 | 19 | 20 | if __name__ == '__main__': 21 | main() 22 | -------------------------------------------------------------------------------- /dashboard/urls.py: -------------------------------------------------------------------------------- 1 | """dashboard URL Configuration 2 | 3 | The `urlpatterns` list routes URLs to views. For more information please see: 4 | https://docs.djangoproject.com/en/2.2/topics/http/urls/ 5 | Examples: 6 | Function views 7 | 1. Add an import: from my_app import views 8 | 2. Add a URL to urlpatterns: path('', views.home, name='home') 9 | Class-based views 10 | 1. Add an import: from other_app.views import Home 11 | 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') 12 | Including another URLconf 13 | 1. Import the include() function: from django.urls import include, path 14 | 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) 15 | """ 16 | from django.contrib import admin 17 | from django.urls import path 18 | from reports.views import home_view, export_data, import_data 19 | urlpatterns = [ 20 | path('admin/', admin.site.urls), 21 | path('', home_view, name="home"), 22 | path('export/', export_data, name="export"), 23 | path('import/', import_data, name="import") 24 | 25 | ] 26 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 coderasha 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /templates/base.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | Reports 9 | 10 | 11 |
12 |

Reports Dashboard

13 | 14 | {% block content %} 15 |

>>Export Data

16 |

>>Import Data

17 | {% endblock %} 18 |
19 | 20 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /reports/views.py: -------------------------------------------------------------------------------- 1 | from django.shortcuts import render 2 | from django.http import HttpResponse 3 | from tablib import Dataset 4 | 5 | from .resources import EmployeeResource 6 | from .models import Employee 7 | 8 | def home_view(request): 9 | return render(request, 'base.html') 10 | 11 | def export_data(request): 12 | if request.method == 'POST': 13 | file_format = request.POST['file-format'] 14 | employee_resource = EmployeeResource() 15 | dataset = employee_resource.export() 16 | if file_format == 'CSV': 17 | response = HttpResponse(dataset.csv, content_type='text/csv') 18 | response['Content-Disposition'] = 'attachment; filename="exported_data.csv"' 19 | return response 20 | elif file_format == 'JSON': 21 | response = HttpResponse(dataset.json, content_type='application/json') 22 | response['Content-Disposition'] = 'attachment; filename="exported_data.json"' 23 | return response 24 | elif file_format == 'XLS (Excel)': 25 | response = HttpResponse(dataset.xls, content_type='application/vnd.ms-excel') 26 | response['Content-Disposition'] = 'attachment; filename="exported_data.xls"' 27 | return response 28 | 29 | return render(request, 'export.html') 30 | 31 | def import_data(request): 32 | if request.method == 'POST': 33 | file_format = request.POST['file-format'] 34 | employee_resource = EmployeeResource() 35 | dataset = Dataset() 36 | new_employees = request.FILES['importData'] 37 | 38 | if file_format == 'CSV': 39 | imported_data = dataset.load(new_employees.read().decode('utf-8'),format='csv') 40 | result = employee_resource.import_data(dataset, dry_run=True) 41 | elif file_format == 'JSON': 42 | imported_data = dataset.load(new_employees.read().decode('utf-8'),format='json') 43 | result = employee_resource.import_data(dataset, dry_run=True) 44 | 45 | if not result.has_errors(): 46 | employee_resource.import_data(dataset, dry_run=False) 47 | 48 | return render(request, 'import.html') 49 | -------------------------------------------------------------------------------- /dashboard/settings.py: -------------------------------------------------------------------------------- 1 | """ 2 | Django settings for dashboard project. 3 | 4 | Generated by 'django-admin startproject' using Django 2.2.5. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/2.2/topics/settings/ 8 | 9 | For the full list of settings and their values, see 10 | https://docs.djangoproject.com/en/2.2/ref/settings/ 11 | """ 12 | 13 | import os 14 | 15 | # Build paths inside the project like this: os.path.join(BASE_DIR, ...) 16 | BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 17 | 18 | 19 | # Quick-start development settings - unsuitable for production 20 | # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ 21 | 22 | # SECURITY WARNING: keep the secret key used in production secret! 23 | SECRET_KEY = 'n&6pl_cufrbhx7oh6maz+*d&s0f+n(3x-detl2je&zt%d3#($3' 24 | 25 | # SECURITY WARNING: don't run with debug turned on in production! 26 | DEBUG = True 27 | 28 | ALLOWED_HOSTS = [] 29 | 30 | 31 | # Application definition 32 | 33 | INSTALLED_APPS = [ 34 | 'django.contrib.admin', 35 | 'django.contrib.auth', 36 | 'django.contrib.contenttypes', 37 | 'django.contrib.sessions', 38 | 'django.contrib.messages', 39 | 'django.contrib.staticfiles', 40 | 'import_export', 41 | 'reports', 42 | ] 43 | 44 | MIDDLEWARE = [ 45 | 'django.middleware.security.SecurityMiddleware', 46 | 'django.contrib.sessions.middleware.SessionMiddleware', 47 | 'django.middleware.common.CommonMiddleware', 48 | 'django.middleware.csrf.CsrfViewMiddleware', 49 | 'django.contrib.auth.middleware.AuthenticationMiddleware', 50 | 'django.contrib.messages.middleware.MessageMiddleware', 51 | 'django.middleware.clickjacking.XFrameOptionsMiddleware', 52 | ] 53 | 54 | ROOT_URLCONF = 'dashboard.urls' 55 | 56 | TEMPLATES = [ 57 | { 58 | 'BACKEND': 'django.template.backends.django.DjangoTemplates', 59 | 'DIRS': [os.path.join(BASE_DIR, 'templates')], 60 | 'APP_DIRS': True, 61 | 'OPTIONS': { 62 | 'context_processors': [ 63 | 'django.template.context_processors.debug', 64 | 'django.template.context_processors.request', 65 | 'django.contrib.auth.context_processors.auth', 66 | 'django.contrib.messages.context_processors.messages', 67 | ], 68 | }, 69 | }, 70 | ] 71 | 72 | WSGI_APPLICATION = 'dashboard.wsgi.application' 73 | 74 | 75 | # Database 76 | # https://docs.djangoproject.com/en/2.2/ref/settings/#databases 77 | 78 | DATABASES = { 79 | 'default': { 80 | 'ENGINE': 'django.db.backends.sqlite3', 81 | 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), 82 | } 83 | } 84 | 85 | 86 | # Password validation 87 | # https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators 88 | 89 | AUTH_PASSWORD_VALIDATORS = [ 90 | { 91 | 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', 92 | }, 93 | { 94 | 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 95 | }, 96 | { 97 | 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', 98 | }, 99 | { 100 | 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', 101 | }, 102 | ] 103 | 104 | 105 | # Internationalization 106 | # https://docs.djangoproject.com/en/2.2/topics/i18n/ 107 | 108 | LANGUAGE_CODE = 'en-us' 109 | 110 | TIME_ZONE = 'UTC' 111 | 112 | USE_I18N = True 113 | 114 | USE_L10N = True 115 | 116 | USE_TZ = True 117 | 118 | 119 | # Static files (CSS, JavaScript, Images) 120 | # https://docs.djangoproject.com/en/2.2/howto/static-files/ 121 | 122 | STATIC_URL = '/static/' 123 | IMPORT_EXPORT_USE_TRANSACTIONS = True --------------------------------------------------------------------------------