简体   繁体   English

Django - 导入 CSV 文件时保留换行符

[英]Django - Keep line breaks when importing CSV file

I am uploading and importing a CSV file in Django.我正在 Django 中上传和导入一个 CSV 文件。 Each row has a "description" field which could have line breaks.每行都有一个“描述”字段,可以有换行符。 Currently all the line breaks are lost when saving to Django TextField and this causes all the formatting to be lost.当前保存到 Django TextField 时所有换行符都会丢失,这会导致所有格式丢失。 The user then has go to the web portal or admin console and manually format the text for the description field.然后,用户转到 Web 门户或管理控制台并手动设置描述字段的文本格式。 This is really tedious and time consuming when you hundreds of records.当您记录数百条记录时,这真的很乏味且耗时。

Is there a way to maintain formatting when importing a CSV file?导入 CSV 文件时有没有办法保持格式?

Currently I am using:目前我正在使用:

file = request.FILES['csv_file']

csv_file_data = [row for row in csv.reader(file.read().splitlines())]   

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)]

I had the same problem when using django-import-export .使用django-import-export时我遇到了同样的问题。

I ended up overriding the import_field method (but do let me know if there is a better way):我最终覆盖了import_field方法(但请告诉我是否有更好的方法):

# 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM