[Answered ]-Django – Keep line breaks when importing CSV file

2πŸ‘

βœ…

From here:

def splitkeepsep(s, sep):
    return reduce(lambda acc, elem: acc[:-1] + [acc[-1] + elem] if elem == sep else acc + [elem], re.split("(%s)" % re.escape(sep), s), [])

Hence:

file = request.FILES['csv_file']

# Updated to reflect OP's comments:
csv_file_data = [row for row in csv.reader(splitkeepsep(file.read(), '\n'), dialect=csv.excel_tab)]
πŸ‘€jrd1

0πŸ‘

I had the same problem when using django-import-export.

I ended up overriding the import_field method (but do let me know if there is a better way):

# admin.py

from django.db.models.fields import TextField


class YourModelResource(resources.ModelResource):

    def import_field(self, field, obj, data, is_m2m=False):
        field_model = YourModel._meta.get_field(field.column_name)
        # keep linebreaks in TextField columns
        if type(field_model) == TextField:
            data[field.column_name] = data[field.column_name].replace('\n', '<br />\n')
        field.save(obj, data, is_m2m)
πŸ‘€raphodn

Leave a comment