我正在尝试使用Django,并使用此代码创建用户
11
12
ss
32
ss
我的问题是,如果我无法创建用户,如何检查用户是否成功创建,以及显示错误消息。
当我运行此代码时,它会创建一个用户但返回值awk '/ss/,/gg/{next}1' file
由于
答案 0 :(得分:3)
检查用户是否具有实际值的pk
属性。如果它被保存在数据库中。
正如用户knbk所述,简单检查如下所示就足够了
if user.pk is not None: # do stuff
答案 1 :(得分:1)
create_user
将导致完整性错误。
def register(request):
try:
user = User.objects.create_user('John', 'lennon@thebeatles.com', 'johnpassword')
except IntegrityError:
# user already exists
status = 'user already exists'
else:
user.last_name = "James"
user.is_active = True
user.save()
status = 'new user was created'
return HttpResponse(status)
对我来说这看起来更好:
def register(request):
try:
# user is active bu default
user = User.objects.create_user('John', 'lennon@thebeatles.com', 'johnpassword', last_name='James')
except IntegrityError:
# user already exists
status = 'user already exists'
else:
status = 'new user was created'
return HttpResponse(status)