【问题标题】:how to make messages showed up in the template如何使消息显示在模板中
【发布时间】:2019-11-26 06:04:35
【问题描述】:

我有一个登录 django 应用程序,如果他们有错误的凭据或者他们是否成功登录,我试图通知用户。

问题是我在 django 中使用了消息框架,但它没有出现在模板中。

views.py

from django.contrib import messages


def login_request(request):
    if request.method == "POST":
        username = request.POST['lognName']
        password = request.POST['lognCode']
        user = authenticate(username = username,password = password)
        if user is not None:
            login(request,user)
            messages.info(request,f"You are now logged in as {username}")
            return redirect("main")
        else:
            messages.error(request,"invalid username or password")

    return render(request,'login.html')

login.html

{% if messages %}
    {% for message in messages %}
        <script>M.toast({html:"{{message}}",classes:'blue rounded',displaylength:2000});</script>
    {% endfor %}
{% endif %}

即使我尝试在 if 语句之外使用,toast 也不起作用

【问题讨论】:

  • 你在页面源代码中看到html了吗?
  • @daniherrera 它显示此错误 Uncaught ReferenceError: M is not defined
  • 看起来是 JS 问题。你在哪里声明 M?
  • @daniherrera 是的,你是对的,我没有导入 js 库。
  • 我发表评论作为答案?

标签: javascript django templates


【解决方案1】:

尝试在里面设置脚本 $(document).ready(function($) { /* foreach message M.toast(...) */ });

我会亲自在一个单独的 js 文件中完成。

如果您想从 js 访问消息对象,请查看此链接:Django Template Variables and Javascript

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-12-23
    • 2019-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多