如何在HTML中显示Forms.py文件 [英] How to show forms.py file in HTML

查看:45
本文介绍了如何在HTML中显示Forms.py文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经从 Django创建了forms.py文件.教程,但没有显示如何以HTML形式显示.我正在使用Django 1.9,非常感谢您的帮助.我正在尝试为该问题创建一个具有4个选择的问题.

I've created the forms.py file from the Django tutorial here, But it doesn't show how to display this in HTML. I'm using Django 1.9 and would really appreciate the help. I'm trying to create a question with 4 choices for said question.

谢谢

forms.py


Question_CHOICES = (
    ('1', '2', '3', '4',)
)
class QuestionForm(forms.Form):
    Q1 = forms.MultipleChoiceField(
         required=True, 
         widget=forms.CheckboxSelectMultiple, 
         choices=Question_CHOICES
    )

推荐答案

在您的 views.py 文件中编写:

def vote_view(request):
    from .forms import QuestionForm
    question_form = QuestionForm()
    return render(request, 'path/to/your/template.html', locals())

然后在您的HTML中写:

Then in your HTML write:

<div>
    {{ question_form.as_p }}
    or
    {{ question_form.as_table }}
</div>

您可以用不同的格式呈现表单.请参见此处.

You can render the form in different formats. See here.

locals()也是Python方便的方法,它将当前作用域(即 vote_view 视图功能)的所有局部变量传递给HTML模板.

Also the locals() is a python convenient way to pass to the HTML template all the local variables of the current scope (i.e of the vote_view view function).

别忘了,当然可以像下面这样将视图链接到您的基本 urls.py 文件:

Do not forget, of course to link the view to your base urls.py file like this:

from your_app.views import vote_view

urlpatterns = [...]  # the previous urls (if any)
urlpatterns += [ url(r'^polls/$', vote_view, name='polls'), ]

[UPDATE] :此类型的表单字段的 Question_CHOICES 格式错误.您应该这样定义它:

[UPDATE]: The format of your Question_CHOICES is wrong for this type of form field. You should to define it this way:

Question_CHOICES = (
    ('1', '1'),
    ('2', '2'),
    ('3', '3'),
    ('4', '4'),
)

然后将通过 {{question_form}} {{question_form.as_p}} {{question_form.as_table}呈现到HTML模板} 或其他任何东西!

Then is will render to your HTML template either via {{ question_form }} or {{ question_form.as_p }} or {{ question_form.as_table }} or whatever!

这篇关于如何在HTML中显示Forms.py文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆