简体   繁体   English

django 模板中不显示表单

[英]django don't show form in template

django dont show my form in my template where is the problem? django 不在我的模板中显示我的表单 问题出在哪里?

forms.py forms.py

from django import forms

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

views.py视图.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)

template模板

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

A GET request is used to retrieve the page, whereas a POST request is used to submit the form. GET 请求用于检索页面,而 POST 请求用于提交表单。 Here you only construct a form in the POST request.这里只在 POST 请求中构造一个表单。 For the GET request, you did not even define a context , which will thus raise an error.对于 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)

take the form before request.post like this:在 request.post 之前采取这样的形式:

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

note: context and return is not in 'if' block注意:上下文和返回不在“if”块中

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM