Djangoajax:in-call不做任何更改

2024-05-05 23:46:47 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我为我的用户模型创建了这个ajax视图

def new_notification(request):
    user = request.user
    user.profile.notifications += 1
    user.save()

    return JsonResponse(serializers.serialize('json', [user]), safe=False)

我用一个整型通知字段扩展了我的用户模型,但是当我调用ajax时,它没有给我的通知模型+1,有人知道发生了什么吗

我的URL.py

url(r'^ajax/new_notification/$', new_notification),

还有我的ajax电话

$.get('/ajax/new_notification/')

我的用户配置文件模型

class ProfileImage(models.Model):
    """
    Profile model
    """
    user = models.OneToOneField(
        verbose_name=_('User'),
        #to=settings.AUTH_USER_MODEL,
        to = User,
        related_name='profile',
        on_delete=models.CASCADE
    )
    avatar = models.ImageField(upload_to='profile_image')
    notifications = models.FloatField(default='0')

Tags: to用户name模型视图newmodelsrequest
1条回答
网友
1楼 · 发布于 2024-05-05 23:46:47

因此,更改url:

url(r'^ajax/new_notification/(?P<username>[a-zA-Z0-9/_\.-]*)', new_notification),

然后,更改查看功能:

def new_notification(request, username):
    #user = request.user
    user = User.objects.get(username=username)
    
    print(user.profile)
    print(user.profile.notifications)
    user.profile.notifications += 1
    print(user.profile.notifications)
    user.profile.save()
    
    #user.save()

    return JsonResponse(serializers.serialize('json', [user]), safe=False)

然后,在模板中的ajax调用中,将url更改为:/ajax/new_notification/{{ user.username }}

相关问题 更多 >