- changed status to open
Adding a URL for number of unread messages
I understand that there is a template tag for number of unread messages. However, for my single-page application the header with the notification icon is loaded only once and I need a way to get number of unread messages through AJAX. It would be nice to have a URL for number of unread messsages, something like
def get_messages_count(request, *args, **kwargs):
return JsonResponse({
'unread_count':
0 if request.user.is_anonymous else Message.objects.inbox_unread_count(request.user)
})
Thanks.
Comments (11)
-
repo owner -
This is different from
#108. The frontend does not have to poll repeatedly, but for example when the page is loaded, an AJAX call could be used to query the number of new messages, and then the user can click the icon to go to the inbox. I was trying to figure out how a way to get “unread_count” easily. -
repo owner There are already two ways to get the count, when the page is served:
- with a context processor: postman.context_processors.inbox
- with a tag: postman_unread
Can you say why you would need to issue an additional ajax request afterwards?
-
Because I am using AJAX calls to get the count. More specifically, I have a header with the “original” count. The webpage works similar to a Single Page Application with its content frequently updated but not the header so I need to get the updated message count through an AJAX call.
-
repo owner The implementation is now committed in repository.
Could you have a try before a public release? -
Tried and did not work because I am using `hx-get` from
htmx
to make the AJAX call, which does not have theXMLHttpRequest
header. I do not think theis_ajax
check is necessary and according to https://docs.djangoproject.com/en/3.1/ref/request-response/ , is_ajax has been deprecated since version 3.1.
-
repo owner Thanks for the hint, you’re right. The restriction has been removed.
-
Thanks. I can confirm that the new view works fine. Please close the issue since somehow my original request was posted as a “formal user”.
-
repo owner I made a change in the case of a not logged-in user, to return a 401 Unauthorized instead of the usual login page, not appropriate to ajax calls.
-
That is ok. At least in my application anonymous users do not send or receive messages.
-
repo owner - changed status to resolved
- Log in to comment
It looks like the abandoned issue
#108. Does the suggested solution suit you?