异常堆栈
File "E:\python35\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view
return view_func(request, *args, **kwargs)
File "E:\pycharm\mysites\account\views.py", line 129, in myself_edit
userprofile = UserProfiles.objects.get(user=request.user) if hasattr(request.user, 'userprofile') else UserProfile.objects.create(user=request.user)
NameError: name 'UserProfile' is not defined
[04/Jan/2019 23:58:38] "GET /account/edit-myinformation/ HTTP/1.1" 500 72461
Internal Server Error: /account/myinformation/
Traceback (most recent call last):
File "E:\python35\lib\site-packages\django\db\backends\utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
File "E:\python35\lib\site-packages\django\db\backends\sqlite3\base.py", line 296, in execute
return Database.Cursor.execute(self, query, params)
sqlite3.IntegrityError: UNIQUE constraint failed: account_userprofiles.user_id
The above exception was the direct cause of the following exception:
File "E:\python35\lib\site-packages\django\db\backends\utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
File "E:\python35\lib\site-packages\django\db\backends\sqlite3\base.py", line 296, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils.IntegrityError: UNIQUE constraint failed: account_userprofiles.user_id
异常堆栈
DoesNotExist: User matching query does not exist/
File "E:\pycharm\mysites\account\views.py", line 71, in myself
userprofile = UserProfiles.objects.get(user=request.user)
File "E:\python35\lib\site-packages\django\db\models\manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "E:\python35\lib\site-packages\django\db\models\query.py", line 399, in get
self.model._meta.object_name
account.models.UserProfiles.DoesNotExist: UserProfiles matching query does not exist.
分析:
当显示结果中不存在“值”时,会返回如标题的错误(DoesNotExist: User matching query does not exist.),程序终止运行。终止运行意味着后面的代码不再被执行,故而得不到自己想要的结果。
Django docs define this clearly, I miss that, sorry
Storing additional information about users
If you'd like to store additional information related to your users, Django provides a method to specify a site-specific related model -- termed a "user profile" -- for this purpose.
To make use of this feature, define a model with fields for the additional information you'd like to store, or additional methods you'd like to have available, and also add a OneToOneField named user from your model to the User model. This will ensure only one instance of your model can be created for each User. For example:
from django.contrib.auth.models import User class UserProfile(models.Model): # This field is required. user = models.OneToOneField(User) # Other fields here accepted_eula = models.BooleanField() favorite_animal = models.CharField(max_length=20, default="Dragons.")
To indicate that this model is the user profile model for a given site, fill in the setting AUTH_PROFILE_MODULE with a string consisting of the following items, separated by a dot:
The name of the application (case sensitive) in which the user profile model is defined (in other words, the name which was passed to manage.py startapp to create the application). The name of the model (not case sensitive) class.
For example, if the profile model was a class named UserProfile and was defined inside an application named accounts, the appropriate setting would be:
AUTH_PROFILE_MODULE = 'accounts.UserProfile'
When a user profile model has been defined and specified in this manner, each User object will have a method -- get_profile() -- which returns the instance of the user profile model associated with that User.
The method get_profile() does not create a profile if one does not exist. You need to register a handler for the User model's django.db.models.signals.post_save signal and, in the handler, if created is True, create the associated user profile:
in models.py
from django.contrib.auth.models import User from django.db.models.signals import post_save
# definition of UserProfile from above # ... def create_user_profile(sender, instance, created, **kwargs): if created: UserProfile.objects.create(user=instance) post_save.connect(create_user_profile, sender=User)
解决方法
@login_required(login_url='account/login/')
def myself(request):
user = User.objects.get(username=request.user.username)
#userprofiles = UserProfiles.objects.get(user=user)
#userinfo = UserInfo.objects.get(user=user)
# userprofile = UserProfiles.objects.get(user=request.user)
# userinfo = UserInfo.objects.get(user =request.user)
userprofile = UserProfiles.objects.get(user=request.user) if hasattr(request.user,
'userprofiles') else UserProfiles.objects.create(
user=request.user)
userinfo = UserInfo.objects.get(user=request.user) if hasattr(request.user,
'userinfo') else UserInfo.objects.create(
user=request.user)
return render(request,'account/myself.html',{'user':user,'userinfo':userinfo,'userprofile':userprofile})
解决方法
您确定该用户的UserProfile对象是否存在?Django不会自动为您创建它。
你可能想要的是这个:
u = User.objects.get(id=1)
zm = u.get_profile()
try:
user = UniversityDetails.objects.get(email=email)
except UniversityDetails.DoesNotExist:
user = None
I also see you're storing your passwords in plaintext (a big security no-no!). Why don't you use the built-in auth system?
我还看到你将密码存储在明文(一个很大的安全禁忌!)你为什么不使用内置的自动签名系统呢?
I also had this problem. It was caused by the development server not deleting the django session after a debug abort in Aptana, with subsequent database deletion. (Meaning the id of a non-existent database record was still present in the session the next time the development server started)
我也有这个问题。这是由于开发服务器在Aptana中的调试中止之后没有删除django会话,并随后删除数据库而导致的。(意味着不存在的数据库记录的id在下一次开发服务器启动时仍然存在于会话中)
To resolve this during development, I used
为了在开发过程中解决这个问题,我使用了
request.session.flush()
In case anybody is here and the other two solutions do not make the trick, check that what you are using to filter is what you expect:
如果有人在这里,而其他两个解决方案没有达到这个目的,请检查您用来过滤的是您所期望的:
user = UniversityDetails.objects.get(email=email)
is email a string, or a None? or an integer?
电子邮件是字符串,还是没有?还是一个整数?
You may try this way. just use a function to get your object
你可以试试这种方法。只需使用一个函数来获取对象
def get_object(self, id):
try:
return UniversityDetails.objects.get(email__exact=email)
except UniversityDetails.DoesNotExist:
return False
As mentioned in Django docs, when get
method finds no entry or finds multiple entries, it raises an exception, this is the expected behavior:
如Django文档中所提到的,当get方法没有发现条目或发现多个条目时,它会引发异常,这是预期的行为:
get() raises MultipleObjectsReturned if more than one object was found. The MultipleObjectsReturned exception is an attribute of the model class.
如果发现了多个对象,那么get()将引发multipleobjectsreturn。multipleobjectsreturn异常是模型类的一个属性。
get() raises a DoesNotExist exception if an object wasn’t found for the given parameters. This exception is an attribute of the model class.
如果没有找到给定参数的对象,则引发一个DoesNotExist异常。这个异常是model类的一个属性。
Using exceptions is a way to handle this problem, but I actually don't like the ugly try-except
block. An alternative solution, and cleaner to me, is to use the combination of filter
+ first
.
使用异常是处理这个问题的一种方法,但实际上我不喜欢丑陋的try-except块。另一种解决方案,对我来说更干净,是先使用filter + first的组合。
user = UniversityDetails.objects.filter(email=email).first()
When you do .first()
to an empty queryset it returns None
. This way you can have the same effect in a single line.
当您执行.first()到空的queryset时,它将返回None。这样你就可以在一行中得到相同的效果。
The only difference between catching the exception and using this method occurs when you have multiple entries, the former will raise an exception while the latter will set the first element, but as you are using get
I may assume we won't fall on this situation.
捕获异常和使用此方法的惟一区别是,当您有多个条目时,前者会引发异常,而后者将设置第一个元素,但是当您使用get时,我可能会认为我们不会陷入这种情况。
如果您确定该配置文件存在(并且您已正确设置AUTH_PROFILE_MODULE),则User模型已经有一个帮助方法来处理:
|