如何解决django ajax:用户匹配查询不存在
所以我做了一个django ajax,每次有新消息时,我添加到我的用户模型中的通知对象将为+1,问题是我不知道为什么会给我这个错误:
django.contrib.auth.models.User.DoesNotExist: User matching query does not exist.
这是我的代码:
views.py:
def count_notification(request):
user = request.user
obj = user.profile.objects.get(pk=1)
obj.notifications = obj.notifications +1
obj.save()
response_data = {'success':1}
return HttpResponse(json.dumps(response_data),content_type="application/json")
urls.py:
path('messages/notification/',count_notification)
html文件js
// Add the notification val
$.get('notification/')
models.py:
class ProfileImage(models.Model):
"""
Profile model
"""
user = models.OneToOneField(
verbose_name=_('User'),to=settings.AUTH_USER_MODEL,related_name='profile',on_delete=models.CASCADE
)
avatar = models.ImageField(upload_to='profile_image')
notifications = models.FloatField(default='0')
感谢您的帮助
解决方法
obj = user.profile.objects.get(pk=1)
我认为您的应用程序正在与许多用户打交道,每个用户都有自己的个人资料以及自己的通知计数,因此,为什么要将id / pk固定为1,您需要获取相关的个人资料,而不是对ID进行硬编码
在下面尝试此代码
def count_notification(request):
user = request.user
user.profile.notifications += 1
user.profile.save()
response_data = {'success':1}
return HttpResponse(json.dumps(response_data),content_type="application/json")
并更改
notifications = models.FloatField(default='0')
到
notifications = models.IntegerField(default='0')
由于通知计数是一个整数,而不是浮点数n,并且不要忘记重新运行迁移,因此确实有意义。
更新
我想您尚未在User
中定义自定义settings.py
模型,在这种情况下,您需要在models.py
中进行一些更改
参阅https://docs.djangoproject.com/en/3.0/topics/auth/customizing/#reusable-apps-and-auth-user-model
from django.contrib.auth import get_user_model # get the default User model
User = get_user_model()
class ProfileImage(models.Model):
"""
Profile model
"""
user = models.OneToOneField(
verbose_name=_('User'),# to=settings.AUTH_USER_MODEL,# you don't need this since you didn't
# defined a custom User model in
# setting.py
to = User,# HERE
related_name='profile',on_delete=models.CASCADE
)
avatar = models.ImageField(upload_to='profile_image')
notifications = models.IntegerField(default='0') # change the field type
更新2
from django.contrib.auth import get_user_model
User = get_user_model()
..
def count_notification(request):
# user = request.user
user = User.objects.filter(id=request.user.id).first() # HERE
user.profile.notifications += 1
user.profile.save()
response_data = {'success':1}
return HttpResponse(json.dumps(response_data),content_type="application/json")
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。