[Django]-Is it possible to limit the number of messages a user can send a day with Django postman?

1👍

Answer to my own question.

After a lot of research and hours of unsuccessful tests, I found a way to do so (while this is not integrated in django-postman app itself). Actually it may sounds basic for a lot of people, but nevermind I am still going to share my solution, which relies on decorators.

At first I tried to create my own ReplyView, but it was a lot of pain to make it work with django postman: I did not succeed, so if someone knows how to do that I would appreciate to read him/her/apache.

Also, please notice I did everything I did in order not to edit Django postman code (as my modifications would be crushed by any Django Postman update).


1. Creating your custom decorator

In your decorators.py file (that you have to create if you don’t have one), you have to create the decorator you will use to decorate default Postman ReplyView. I will assume you associated a profile model to user, as it is your profile that will memorize the number of messages sent a day, and a canSendMessage method that will check if connected user is allowed to send a new message (returns True if user quota is reached).

from django.contrib import messages
from django.shortcuts import redirect

def count_messages_sent():
    def decorator_fun(func):
        def wrapper_func(request, *args, **kwargs):

            user_profile = request.user.profile

            # we check if user is allowed to send a new message
            if not user_profile.canSendMessage(): 
                messages.error(request, "Messages limit reached")
                return redirect('postman:inbox')

            # if he is, we call expected view, and update number of messages sent
            called_func = func(request, *args, **kwargs)
            user_profile.nbr_messages_sent_today += 1
            user_profile.save()

            return called_func
        return wrapper_func
    return decorator_fun

2. Using your custom decorator

As I said before:

  • I do not want to edit original postman code,
  • I do not want to create custom views.

So, we will have to decorate Django Postman ReplyView! How? Through your app urls.py file:

from postman import views as postman_views
from yourApp.decorators import count_messages_sent

urlpatterns = [
    ... 
    url(r'^messages/reply/(?P<message_id>[\d]+)/$', count_messages_sent()(postman_views.ReplyView.as_view()), name='custom_reply'),
]

And that’s it! It works like a charm.

If you have any idea of improvement, please do not hesitate to share!

1👍

as a simple idea the inserting of new msg in database should be with a condition to limit their numbers (the count of the previous msg isn’t > max )
another method : you will show the input of the msg jsut when (selet * form table where userid=sesion and count(usermsg)< max )

Leave a comment