首页 > 解决方案 > 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.
          )
     )

那么,我该如何实现呢?

标签: pythondjango

解决方案


推荐阅读