首页 > 解决方案 > /contacts/import 处的 IntegrityError

问题描述

在 django 中,当我要导入 csv 文件并解析它时,我得到以下错误

django.db.utils.IntegrityError:NOT NULL 约束失败:inven_app_clientcontact.author_id [29/Apr/2019 17:56:32]“POST /contacts/import HTTP/1.1”500 188071

这是我的代码

   @login_required
def contact_upload(request):
    template = 'site/contact_upload.html'
    prompt = {
        'order': 'Order of the CSV should be client_name, client_company_name, email, work_phone'
    }

if request.method == 'GET':
    return render(request, template, prompt)

csv_file = request.FILES['file']

if not csv_file.name.endswith('.csv'):
    messages.error(request, 'This is not a csv file')

data_set = csv_file.read().decode('utf-8')
io_string = io.StringIO(data_set)
next(io_string)

for column in csv.reader(io_string, delimiter=',', quotechar='|'):
    _, created = ClientContact.objects.filter(author=request.user).update_or_create(
        client_name=column[0],
        client_company_name=column[1],
        email=column[2],
        work_phone=column[3]
    )
context = {}

return render(request, template, context)

任何帮助都会得到帮助。谢谢你。如果需要任何代码,请告诉我

标签: pythondjangopython-3.x

解决方案


该错误表明您正在尝试在没有用户的情况下保存对象。您没有显示完整的回溯,它将准确显示错误发生的位置,但它可能在您的update_or_create调用中 - 您应该设置author默认值或将其添加到 kwargs。例如:

_, created = ClientContact.objects.filter().update_or_create(
    client_name=column[0],
    client_company_name=column[1],
    email=column[2],
    work_phone=column[3],
    author=request.user,
)

推荐阅读