【问题标题】:In Django I want to show a Textarea only during post在 Django 中,我只想在发布期间显示 Textarea
【发布时间】:2015-09-22 14:21:56
【问题描述】:

我的 django 项目有一个简单的页面

  1. 带有 2 个单选按钮的表单
  2. 一个字符字段
  3. 提交

按下提交时。 在我的views.py中,如何捕获选定的单选按钮值和char字段的值

提交后,应使用新的文本区域再次重新加载相同的网页 该文本区域应包含 Radio selection + char field concatenation 的值

到目前为止,我已经创建了基本表单,html 视图。 我的主要问题是

  1. 我无法创建可基于 Get/Post 隐藏的文本区域
  2. 从表单中捕获值并连接,然后在新文本区域中再次显示。

views.py

def index(request):
form=SfvForm()
if request.method == 'POST':
f = SfvForm(request.POST)
    if f.is_valid():
        form.result_text("hi")
        return HttpResponseRedirect('index.html',{'posted':"posted"},{'form':form})
    else:
        return render_to_response("index.html",{"form":form} , context_instance = RequestContext(request))
else:
    return render(request,'index.html',{'form':form})

forms.py

class SfvForm(forms.Form):
CHOICES=[('production','production'),('stage','stage')]
selected_env=forms.ChoiceField(choices=CHOICES, widget=forms.RadioSelect(), )
table_name=forms.CharField(required=True)
result_text=forms.CharField() /*Making it as text area is not displaying the form element at all*/

index.html

<!DOCTYPE html>
<html>
<head>
    <title>SFV</title>
</head>

<body>
    <h1> hello world!</h1>
    <form id="form" method="post" action="/sfv/">
        {% csrf_token %}
        {{ form.as_p }}

    </form>
    <form id="form" method="get" action="/sfv/">
        {% csrf_token %}
        {{ form.as_p }}
        <input type="submit" value="submit"/>
    </form>

    </body>
</html>

【问题讨论】:

  • 你为什么不写 2 个不同的页面? (一个与第一个表单,一个与第二个表单)并在表单成功提交后重定向到第二个?
  • 假设它像一个计算器。一旦显示结果,同一页面将用于提供更多输入。我不希望用户来回遍历。
  • 好的,你看我下面的回答了吗?

标签: python html django


【解决方案1】:

因为当你重定向时:

return HttpResponseRedirect('index.html',{'posted':"posted"},{'form':form})

您需要使用您之前发布的form 值来populate the new form

def index(request):
    form=SfvForm() #<- populate here

【讨论】:

    猜你喜欢
    • 2019-01-25
    • 2018-07-09
    • 1970-01-01
    • 1970-01-01
    • 2021-12-26
    • 1970-01-01
    • 2015-09-15
    • 2020-12-26
    • 1970-01-01
    相关资源
    最近更新 更多