Created
December 9, 2016 12:20
-
-
Save Crocmagnon/189a68e102df6a579f7a68c669ef8c95 to your computer and use it in GitHub Desktop.
Import from Excel into DB
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import os | |
| from django.contrib import messages | |
| from django.core.exceptions import ValidationError | |
| from django.forms import forms | |
| from django.shortcuts import redirect, render | |
| from xlrd import open_workbook | |
| def validate_import_extension(value): | |
| """ | |
| Credits to http://stackoverflow.com/a/8826854/2758732 | |
| """ | |
| ext = os.path.splitext(value.name)[1] | |
| valid_extensions = ['.xls', '.xlsx'] | |
| if ext not in valid_extensions: | |
| raise ValidationError('Type de fichier non autorisé !') | |
| class ProductImportForm(forms.Form): | |
| file = forms.FileField(required=True, label='Fichier', validators=[validate_import_extension]) | |
| def reset_products(request, factory_pk): | |
| """ | |
| View | |
| """ | |
| products = Product.objects.filter(factory=factory_pk) | |
| context = { | |
| 'products': products | |
| } | |
| if request.method == 'POST' or request.method == 'DELETE': | |
| form = ProductImportForm(request.POST, request.FILES) | |
| if form.is_valid(): | |
| products.delete() | |
| with open_workbook(file_contents=request.FILES['file'].read()) as wb: | |
| for sheet in wb.sheets(): | |
| number_of_rows = sheet.nrows | |
| number_of_columns = sheet.ncols | |
| headers = [] | |
| for row in range(number_of_rows): | |
| if row == 0: | |
| for col in range(number_of_columns): | |
| headers.append(sheet.cell(row, col).value) | |
| else: | |
| values = {} | |
| for col in range(number_of_columns): | |
| value = sheet.cell(row, col).value | |
| values[headers[col]] = value | |
| product = Product(**values) | |
| product.factory_id = factory_pk | |
| product.save() | |
| messages.success(request, 'Produits importés') | |
| return redirect('codes:factory_home', factory_pk=factory_pk) | |
| else: | |
| messages.error(request, 'Formulaire invalide') | |
| else: | |
| form = ProductImportForm() | |
| context['form'] = form | |
| return render(request, 'codes/product/import.html', context) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment