所以我做了一个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')
感谢您的帮助
答案 0 :(得分:1)
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
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")