【问题标题】:django don't show form in templatedjango不在模板中显示表单
【发布时间】:2020-12-19 13:12:20
【问题描述】:

django 不在我的模板中显示我的表单 问题出在哪里?

forms.py

from django import forms

class QuestionForm(forms.Form):
    massage = forms.CharField(widget=forms.TextInput)

views.py

from cheatexam_question.forms import QuestionForm
def newquestion(request):
    if request.method == 'POST':
        form = QuestionForm(request.POST)
        context = {
            'form': form
        }
    return render(request, 'homepage.html', context)

模板

        <form method="post">
            {% csrf_token %}
            {{ form }}
      <input class="btn btn-warning form-control" type="submit" value="ثبت سوال">
        </form>

【问题讨论】:

  • 你只为一个 POST 请求构建这个,对于一个 GET 请求,这可能会引发错误。
  • 当没有请求被执行时,你需要一个 else 来显示表单。类似于:else: form = QuestionForm()

标签: python django django-views django-forms django-templates


【解决方案1】:

GET 请求用于检索页面,而 POST 请求用于提交表单。这里只在 POST 请求中构造一个表单。对于 GET 请求,您甚至没有定义 context,因此会引发错误。

from cheatexam_question.forms import QuestionForm

def newquestion(request):
    if request.method == 'POST':
        form = QuestionForm(request.POST)
        # …
    else:  # GET request
        form = QuestionForm()
    context = {
        'form': form
    }
    return render(request, 'homepage.html', context)

【讨论】:

    【解决方案2】:

    在 request.post 之前填写表格,如下所示:

    def newquestion(request):
        form = QuestionForm(request.POST or None)
            if form.is_valid():
            .
            .
        context = {'form':form}
        retrun render(request , 'template.html' , context)
    

    注意:上下文和返回不在“if”块中

    【讨论】:

    猜你喜欢
    • 2021-09-06
    • 2021-07-25
    • 2018-04-07
    • 1970-01-01
    • 1970-01-01
    • 2014-08-12
    • 2011-10-11
    • 2018-03-21
    • 1970-01-01
    相关资源
    最近更新 更多