Django表单未在HTML中呈现

2024-04-25 06:25:04 发布

您现在位置:Python中文网/ 问答频道 /正文

**renders**的视图

def codequestion(request, question_id):
    question = Question.objects.get(pk=question_id)
    return render(request, 'polls/codequestion.html', {'question': question})

提交调用的视图是

^{pr2}$

班级

from django import forms

class CodeForm(forms.Form):
    solution = forms.CharField(widget=forms.Textarea)

模板

<form action="{% url 'codequestion_evaluate' question.id %}" method="post">
{% csrf_token %}
{{form.as_p}}   
<input type="submit" value="Submit" />
</form>

我没有在HTML页面中显示表单字段,我只能看到submit按钮。在


Tags: form视图idgetreturnobjectsrequestdef
3条回答

假定要显示未填充表单的视图根本不会创建表单对象。它应该创建一个表单对象并将其传递给模板,如下所示:

def codequestion(request, question_id):
    question = Question.objects.get(pk=question_id)
    form = CodeForm()
    return render(request, 'polls/codequestion.html', {'question': question, 'form': form})

{但是你最好还是跟着。为此,您应该:

  1. 删除codequestion。所有操作(显示未填写的表单、显示有错误的已提交表单、处理正确提交的表单)将由单个视图处理。

  2. 配置url路由,使codequestion_evaluate视图处理显示未填充表单的页面。

  3. 更改codequestion_evaluate使其遵循模式:

    def codequestion_evaluate(request, question_id):
        if request.method == 'POST':
            form = CodeForm(request.POST)
            if form.is_valid():
                # The form has been submitted and is valid
                # process the data and redirect to a "thank you" page
                data = form.cleaned_data
                return HttpResponseRedirect('/thanks/')
            else:
                # just display an empty form
                form = CodeForm()
        # you can optionally add 'question' if you need it in your template
        question = Question.objects.get(pk=question_id)
        return render(request, 'polls/codequestion.html', {'form': form, 'question': question})
    

form引用上下文数据中的一个变量,因为您没有将它包含在上下文数据中,它找不到它,因此没有任何要呈现的内容,您需要包含它。在

def codequestion(request, question_id):

    question = Question.objects.get(pk=question_id)
     return render(request, 'polls/codequestion.html',
                   {'question': question, 'form': CodeForm()})

试着换衣服

class CodeForm(forms.Form):

^{pr2}$

我也遇到了同样的问题,但问题解决了。在

相关问题 更多 >