So I made this ajax view for my user model
JavaScript
x
7
1
def new_notification(request):
2
user = request.user
3
user.profile.notifications += 1
4
user.save()
5
6
return JsonResponse(serializers.serialize('json', [user]), safe=False)
7
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
JavaScript
1
2
1
url(r'^ajax/new_notification/$', new_notification),
2
and my ajax call
JavaScript
1
2
1
$.get('/ajax/new_notification/')
2
my user profile model
JavaScript
1
14
14
1
class ProfileImage(models.Model):
2
"""
3
Profile model
4
"""
5
user = models.OneToOneField(
6
verbose_name=_('User'),
7
#to=settings.AUTH_USER_MODEL,
8
to = User,
9
related_name='profile',
10
on_delete=models.CASCADE
11
)
12
avatar = models.ImageField(upload_to='profile_image')
13
notifications = models.FloatField(default='0')
14
Advertisement
Answer
So, change url:
JavaScript
1
2
1
url(r'^ajax/new_notification/(?P<username>[a-zA-Z0-9/_.-]*)', new_notification),
2
Then, change the view function:
JavaScript
1
14
14
1
def new_notification(request, username):
2
#user = request.user
3
user = User.objects.get(username=username)
4
5
print(user.profile)
6
print(user.profile.notifications)
7
user.profile.notifications += 1
8
print(user.profile.notifications)
9
user.profile.save()
10
11
#user.save()
12
13
return JsonResponse(serializers.serialize('json', [user]), safe=False)
14
Then, in your ajax call in the template, change the url to: /ajax/new_notification/{{ user.username }}