python - 如何从表单 Django 引导页面
问题描述
我正在开发一个字典应用程序,我允许用户通过表单输入一个单词。当在表单中输入单词并按下提交按钮时,我希望表单保持在同一页面上,但是当用户输入单词并按下提交时,表单消失,只留下提交按钮和搜索结果
这是字典/表单代码
class NameForm(forms.Form):
your_name = forms.CharField(max_length=100, label=False)
字典/视图代码
def index(request):
if request.method == 'POST':
form = NameForm(request.POST)
if form.is_valid():
word = form.cleaned_data['your_name']
print(word)
if Dictionary.get_verb(word):
verb = Dictionary.get_verb(word)
else:
verb = False
print(verb)
if Dictionary.get_noun(word):
noun = Dictionary.get_noun(word)
else:
noun = False
print(noun)
synonyms = Dictionary.get_synonyms(word)
print(synonyms)
form = NameForm()
context = {
'verb':verb,
'noun':noun,
'synonyms':synonyms,
}
return render(request,'index.html' ,context)
else:
form = NameForm()
context = {
'form': form,
}
return render(request, 'index.html', context)
和 index.html
form action="" method="post">
{% csrf_token %}
{{form}}
<br>
<input type="submit" value="Submit">
</form>
<hr>
{% if noun %}
<h2>Noun</h2>
{% for noun_word in noun %}
<p>{{noun_word}}</p>
{% endfor %}
{% else %}
<!-- print nothing-->
{% endif %}
<br>
<hr>
{% if verb %}
<h2>Verb</h2>
{% for verb_info in verb %}
<p>{{verb_info}}</p>
{% endfor %}
{% else %}
<!-- print nothing-->
{% endif %}
<h2>Synonyms</h2>
{% if synonyms %}
{% for synonym_info in synonyms %}
<p>{{synonym_info}}</p>
{% endfor %}
{% else %}
<!-- print nothing-->
{% endif %}
我创建了一个字典类来与 Dictionary API 交互。但我的挑战是我该如何去做,以便在提交表单时它会返回表单和按钮以及下面的结果。谢谢!!
解决方案
您可以在 forms.py 中添加渲染,也可以在模板中设置操作
<form class="postForm" action="{% url 'name of your url' %}" method="POST">
推荐阅读
- sql - SQL 查询 - 在连续行中累积连接字符串
- azure - 创建索引和技能 Azure 认知搜索
- javascript - 异步函数 Javascript 中的 Cookie
- php - 使用elementor表单更新mysql中的表
- excel - Excel VBA - 对于每个循环备选方案
- apache-spark - org.apache.spark.SparkException:作业因 pyspark 中的阶段失败而中止
- keycloak - Keycloak 不会重定向到 https
- javascript - 使用 nightwatchjs 定位并检查脚本(在网页内)是否正确
- powerbi - 尝试使用 PowerBI 显示 Azure 流分析的窗口日期
- java - Android Firebase 身份验证,无法访问调试中可见的用户 Twitter 数据