回答我自己的问题。
经过大量研究和数小时不成功的测试,我找到了一种方法(虽然这没有集成在 django-postman 应用程序本身中)。实际上,对于很多人来说这听起来很基础,但没关系,我仍然会分享我的解决方案,它依赖于decorators。
起初我尝试创建自己的ReplyView,但让它与 django postman 一起工作很痛苦:我没有成功,所以如果有人知道怎么做,我会很感激阅读他/她/阿帕奇。
另外,请注意我所做的一切都是为了不编辑 Django postman 代码(因为我的修改会被任何 Django Postman 更新破坏)。
1。创建您的自定义decorator
在您的decorators.py 文件中(如果没有,则必须创建该文件),您必须创建decorator 用于装饰默认邮递员ReplyView。我将假设您将 profile 模型与用户关联,因为您的个人资料将记住每天发送的消息数量,而 canSendMessage 方法将检查是否允许连接的用户发送新消息(返回True 如果达到用户配额)。
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。使用您的自定义 decorator
正如我之前所说的:
- 我不想编辑原始邮递员代码,
- 我不想创建自定义视图。
所以,我们将不得不装饰 Django Postman ReplyView!如何?通过您的应用程序urls.py 文件:
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'),
]
就是这样!它就像一个魅力。
如果您有任何改进的想法,请随时分享!