python - /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)
任何帮助都会得到帮助。谢谢你。如果需要任何代码,请告诉我
解决方案
该错误表明您正在尝试在没有用户的情况下保存对象。您没有显示完整的回溯,它将准确显示错误发生的位置,但它可能在您的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,
)
推荐阅读
- python - 使用 OMPython 在 OpenModelica 中进行参数化扫描
- javascript - 仅显示 Google App Script 中的最后 12 行
- java - 合并来自单个流的 Kafka 记录值
- javascript - 如何在 React Native 中定位动态内容的剩余部分?
- postgresql - 将 PostgreSQL 表转换为 TimescaleDB 超表
- r - 如何从数据框中获取坐标并放入新的数据框?
- java - 使用 Thymeleaf 发送不同语言的电子邮件
- r - 如何根据 R 中每个集群的固定容量制作集群?
- intel-vtune - 无法在 DPDK 上重现 Intel Vtune 分析示例的结果
- redux - Redux Store 更改时 Redux CreateSelector 未触发