首页 > 解决方案 > 如何从表单 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 交互。但我的挑战是我该如何去做,以便在提交表单时它会返回表单和按钮以及下面的结果。谢谢!!

标签: pythonhtmldjangoformsview

解决方案


您可以在 forms.py 中添加渲染,也可以在模板中设置操作

<form class="postForm" action="{% url 'name of your url' %}" method="POST">

推荐阅读