Django import export has error "Tablib has no format 'None' or it is not registered"

Viewed 1821

I am trying to implement csv import in my application and I have this error, Tablib has no format 'None' or it is not registered.

I am using python 3.5 and Django 2.2. I tried the same code with python 2.7 with Django 1.8 and it worked well. Is there any problem with my code?

My model:

class Stock(models.Model):
    category = models.ForeignKey(Category, on_delete=models.CASCADE, blank=True)
    item_name = models.CharField(max_length=50, blank=True, null=True)
    quantity = models.IntegerField(default='0', blank=False, null=True)
    receive_quantity = models.IntegerField(default='0', blank=True, null=True)
    receive_by = models.CharField(max_length=50, blank=True, null=True)
    issue_quantity = models.IntegerField(default='0', blank=True, null=True)
    issue_by = models.CharField(max_length=50, blank=True, null=True)
    issue_to = models.CharField(max_length=50, blank=True, null=True)
    phone_number = models.CharField(max_length=50, blank=True, null=True)
    created_by = models.CharField(max_length=50, blank=True, null=True)
    reorder_level = models.IntegerField(default='0', blank=True, null=True)
    last_updated = models.DateTimeField(auto_now_add=False, auto_now=True)

    def __str__(self):
        return self.item_name

Resources.py

from import_export import resources
from .models import Stock, Person

class StockResource(resources.ModelResource):
    class Meta:
        model = Stock

Views.py:

from .resources import StockResource


def upload(request):
    if request.method == 'POST':
        stock_resource = StockResource()
        dataset = Dataset()
        new_stock = request.FILES['myfile']

        imported_data = dataset.load(new_stock.read())
        result = stock_resource.import_data(dataset, dry_run=True)  # Test data import

        if not result.has_errors():
            stock_resource.import_data(dataset, dry_run=False)  # Run import

    return render(request, 'csv_import.html')


csv_import.html

    <form method="post" enctype="multipart/form-data">
      {% csrf_token %}
      <input type="file" name="myfile"><br><br>
      <button type="submit">Upload</button>
    </form>

csv_import.csv

1,phone,1,0,9,0,9,9,9,,ssaine,0,2020-06-11,
2,computer,2,0,9,0,9,9,9,9,ssaine,0,2020-08-11,
2 Answers

A couple of things to try:

imported_data = Dataset().load(new_stock.read().decode(), format='csv', headers=False)
print(imported_data)

If that doesn't work, verify exactly what is being returned from new_stock.read(). Is it valid csv data? You can test this out locally before you test on the server.

for those that have headers, leave the headers option out and let django pick the headers itself, also it solves the issue of not saving to the database simplyvic raised. so use

imported_data = Dataset().load(new_stock.read().decode(), format='csv')

Related