【问题标题】:Django ajax: in call does not make any changesDjango ajax:在调用中不做任何更改
【发布时间】:2020-08-13 15:42:34
【问题描述】:

所以我为我的用户模型制作了这个 ajax 视图

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

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

我使用 Integerfield 通知扩展了我的用户模型,但是当我调用 ajax 时,它并没有给我的通知模型 +1,有人知道发生了什么吗?

我的 urls.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')

【问题讨论】:

  • 如果您通过 ajax 执行此操作,request.user 是匿名的。您可以在模板中收集用户,然后将其发送到您的函数:def new_notification(request, user_id):
  • @GAEfan 我该怎么做。我是 Django 新手
  • 显示你的ajax调用代码。
  • @GAEfan 现在我的观点和 ajax 调用在我的问题中

标签: python django ajax django-views


【解决方案1】:

所以,换个网址:

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 }}

【讨论】:

  • 没有改变通知的值
  • 我试了一下,但没有更改通知值
  • 发生这种情况(AttributeError: 'User' object has no attribute 'get_profile')
  • 显示您的用户和用户资料?模型。
  • 好的,试试新代码。 print() 要跟踪的函数。
猜你喜欢
  • 2017-05-30
  • 1970-01-01
  • 2010-12-02
  • 2017-08-17
  • 2019-02-05
  • 2016-03-31
  • 2012-04-16
  • 2013-05-31
  • 1970-01-01
相关资源
最近更新 更多