Skip to content
Advertisement

Django ajax: in call does not make any changes

So I made this ajax view for my user model

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

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

I extends my user model with an Integerfield of notification, but when I call the ajax it does not give +1 to my notification model, does anybody know what is going on?

my urls.py

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

and my ajax call

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

my user profile model

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')

Advertisement

Answer

So, change url:

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

Then, change the view function:

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)

Then, in your ajax call in the template, change the url to: /ajax/new_notification/{{ user.username }}

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement