首页 > 解决方案 > 如何在 Django 1.11 中成功提交表单时“返回索引(请求)”

问题描述

我正在尝试使用 Toastr 在完成表单后传递状态消息。如果表单有效,它会使用“返回索引(请求)”将您返回到索引,我想通过它传递上下文。

我正在使用 Modelforms 运行 Python 3.6 和 Django 1.11。我尝试过传递 context=var_list 以及单独传递变量。

我的views.py的第15-34行

def add(request):
    form = CustomerForm()

    if request.method == "POST":
        form = CustomerForm(request.POST)

        if form.is_valid():
            form.save(commit=True)
            notification_vars = {"toastr_title": "SUCCESS!", 
                                 "toastr_message": "The Customer has been added to the database", 
                                 "toastr_type": "success",}
            return index(request, context=notification_vars) // THIS IS WHAT I NEED TO WORK

    page_vars = { "page_title": "Add Customer", 
                  "page_icon": "fa-address-book",
                  "toastr_title": "", 
                  "toastr_message": "", 
                  "toastr_type": "",
                  "form": form}
return render(request, 'customers/add.html', context=page_vars)

这是我页脚中的烤面包机代码,以及为什么我总是必须将变量作为空白传递,除非我想传递消息

{% if toastr_message %}
    <script>
        var title   = '{{ toastr_title }}',
            message = '{{ toastr_message }}',
            type    = '{{ toastr_type }}',
            options = {};

        toastr[type](message, title, options);
    </script>
{% endif %}

我想要做的是成功提交表单,它将上下文传递回索引页面并将脚本填充到页脚中,以便弹出成功消息。

目前,它回来告诉我我有一个意外的变量上下文,或者如果我直接传递变量,它告诉我有一个语法问题

标签: djangoformstoastr

解决方案


我想到了。我需要确保我的索引可以获取上下文,但也要确保如果没有传递上下文,它仍然可以工作。

def index(request,context={"toastr_title":"","toastr_message":"", "toastr_type":"" }):
    customer_list = Customers.objects.order_by('Name')
    page_vars = { "page_title": "Customers", 
                  "page_icon": "fa-address-book",
                  "toastr_title": context['toastr_title'], 
                  "toastr_message": context['toastr_message'], 
                  "toastr_type": context['toastr_type'],
                  "customer_records": customer_list}
    return render(request, 'customers/index.html', context=page_vars)

推荐阅读