Django - 通过一个文件管理消息字符串

问题描述 投票:0回答:1

我目前发现我的应用程序变得相当大,并且我正在 view.py 中处理许多不同的消息。我必须手动设置在特定视图中返回给用户的每个消息字符串。

现在我的想法是管理我的应用程序返回给用户的所有潜在消息,例如仅由一个文件发出错误或成功消息,这样我就不必为基本相同的事情设置相同的消息字符串三到四次...

示例 - 当前状态:

if example.objects.filter(author=request.user, status='Magic').count() >= config.USER_MAX_MAGIC:
    messages.error(request,
                   'You have reached the maximum amount of Magic.')
    return redirect('magic')

示例 - 通缉状态

from app_messages import xyz # These containing the actual string that should get returned to the user

if example.objects.filter(author=request.user, status='Magic').count() >= config.USER_MAX_MAGIC:
    messages.error(request,
                   xyz)
    return redirect('magic')

我现在的问题是:

xyz
需要是什么样子?这通常是完成错误、成功、信息等消息管理的好主意吗?

提前致谢

python django message
1个回答
0
投票

您只需创建文件,例如 strings.py 并将变量放入其中,例如

maximum_amount_magic = 'You have reached the maximum amount of Magic.'

然后导入字符串并使用:

messages.error(request,settings.maximum_amount_magic)

每次更改strings.py时,您都必须重新加载应用程序才能看到结果。

© www.soinside.com 2019 - 2024. All rights reserved.