for循环中的Python列表错误
我不知道如何描述这个问题,但我会试试看 背景信息 我的Django web应用程序中有一个函数,用户可以在其中导入其他用户。用户可以通过拖放导入转换为JSON 2D数组的.csv文件(使用Papaparse JS) 在视图中,我循环遍历2D数组中的元素,并创建一个“Importuser”,其中包含一些属性,如“firstname”、“lastname”、email等for循环中的Python列表错误,python,arrays,django,python-3.x,csv,Python,Arrays,Django,Python 3.x,Csv,我不知道如何描述这个问题,但我会试试看 背景信息 我的Django web应用程序中有一个函数,用户可以在其中导入其他用户。用户可以通过拖放导入转换为JSON 2D数组的.csv文件(使用Papaparse JS) 在视图中,我循环遍历2D数组中的元素,并创建一个“Importuser”,其中包含一些属性,如“firstname”、“lastname”、email等 class Importuser: firstname = None lastname = None email
class Importuser:
firstname = None
lastname = None
email = None
import_errors = []
def __init__(self, fn, ln, e):
self.firstname = fn
self.lastname = ln
self.email = e
class Importerror:
message = None
type = None
def __init__(self, m, t):
self.message = m
self.type = t
在for循环中,我还验证电子邮件地址,这样就不会有双重用户
data = jsonpickle.decode(method.POST["users"])
users = []
for tempuser in data:
u = validate(Importuser(tempuser[0], tempuser[1], tempuser[2])
users.append(u)
在验证功能中,我检查是否有任何用户使用相同的电子邮件
def validate(user : Importuser):
user_from_db = User.objects.filter(email=user.email)
if user_from_db:
user.import_errors.append(Importerror("The user exists already!", "doubleuser"))
return user
问题
在for循环完成后所有用户都有相同的错误,但在执行for循环时打印每个用户时没有。每个用户中的Importerror对象引用相同的内存位置,但在我的测试导入中,应该只有一个用户出错
test.csv:
Dave,Somename,dave@example.com
Joe,Somename2,joe@example.com
Yannik,Somename3,yannik@example.com <<That's me (exsiting user)
Dave,某个名字,dave@example.com
乔,某个人2,joe@example.com
Yannik,某个名字3,yannik@example.comimport\u errors
是ImportUser
的类属性。它应该是一个实例属性:
class Importuser:
def __init__(self, fn, ln, e):
self.firstname = fn
self.lastname = ln
self.email = e
self.import_errors = []
您已经将import\u errors
定义为类级静态,因此它在Importuser
的所有实例之间共享
见:
对于您的特定问题,请将您的类重写为
class Importuser:
def __init__(self, firstname, lastname, email):
self.firstname = firstname
self.lastname = lastname
self.email = email
self.import_errors = []
class Importerror:
def __init__(self, message, type):
self.message = message
self.type = type
不,因为我检查数据库中的用户是否是非您对的抱歉,但我不能给您更多有关的信息,因为调试器没有告诉我任何信息。我只能看到,在执行for循环时,在最后一个用户得到验证(错误的用户)之前,每个用户在列表中都没有Importerror对象。很抱歉,出现了另一个错误,感谢您的努力