python - Django:将变量/参数传递给视图?
问题描述
我正在尝试从 Django 的视图中传递一个变量以形成表单。
简单地说,我想做的是下面这样的事情。
# views.py
def tmp(request):
if request.method == 'POST':
f = tmpForm(request.POST)
if f.is_valid():
// something more here.
else:
// this will pass nothing to the form
f = tmpForm()
// want to pass variable/parameter to the form
initial = '''{
"hoge": "hogehoge"
}'''
f = tmpForm(initial) // should be something like this maybe?
return render(request, 'tmpapp/tmp.html', {'form': f})
# forms.py
class tmpForm(forms.Form):
// retrieve the variable/parameter and set `initial` or something like that
json = forms.CharField(widget=forms.Textarea, label='', help_text='JSON formatted data here.', initial=
textwrap.dedent(
# '''{
# "hoge": "hogehoge"
# }'''
initial // so you can use the variable like this.
)
)
那么,我该如何实现呢?
解决方案
推荐阅读
- javascript - 我的画布中的触摸事件没有按预期工作,我无法确定它不工作的原因
- thymeleaf - 使用 Thymeleaf 3 在自定义属性中转义 & 符号?
- django - 如何在 django 中发送密码重置电子邮件时显示公司名称而不是电子邮件地址
- linux-kernel - 什么是内核映像?为什么它在嵌入式中是强制性的?
- firebase - 如何在 python 中增加 Firestore 字段值?
- java - 从片段更改工具栏
- c++ - 如何使用 Gmock 连续调用每 n 次返回特定值
- node.js - 使用 Bittex API v3 的 INVALID_CONTENT_HASH 错误
- java - 是否可以将 spring-mvc 中的嵌套映射映射到全局路径?
- php - 将第二个数组推入第一个数组