django - 如何在 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 %}
我想要做的是成功提交表单,它将上下文传递回索引页面并将脚本填充到页脚中,以便弹出成功消息。
目前,它回来告诉我我有一个意外的变量上下文,或者如果我直接传递变量,它告诉我有一个语法问题
解决方案
我想到了。我需要确保我的索引可以获取上下文,但也要确保如果没有传递上下文,它仍然可以工作。
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)
推荐阅读
- typescript - 在打字稿中,有没有办法通过 typeof 数据定义全局窗口的扩展类型?
- javafx - 如何使用 TextFormatter 清除 JavaFx TextField
- scala - 使用 foldLeft 替换字符串中出现的字符
- sass - 尝试使用 @use at-rule 时 SASS 出错
- django - 条件不适用于 Django 模板中的 2 个不同的应用程序
- javascript - 如何使用 div id 渲染多个 div 背景颜色变化
- docker - Kubernetes pod 应用程序与不在容器上的 Mysql 数据库的连接
- flutter - Flutter 中有没有办法在 Dismissible Widget 中捕捉“开始移动”事件?
- r - 如何计算sd?as.double(x) 中的错误:无法将“S4”类型强制转换为“double”类型的向量
- excel - 删除工作表中所有换行符的最有效方法