Django表单没有出现

时间:2014-01-27 20:57:43

标签: django forms django-forms django-cms

我正在使用Django的Form类构建一个带有表单的网页。我已经包含了一些示例代码片段,但我的问题是我已经按照Django文档和Djangobook中的教程,但无法让我的表单实际显示在页面上。

forms.py

from django import forms

class ResearchForm(forms.Form):
    fam_choices = ...
    spec_choices = ...
    family = forms.ChoiceField(choices=fam_choices, required=True)
    species = forms.ChoiceField(choices=spec_choices, required=True)

views.py

from django.http import HttpResponse, HttpResponseRedirect, Http404
from django.shortcuts import render
from mysite.forms import ResearchForm

...

def research(request):
    if request.method == 'GET': 
        form = ResearchForm(request.GET)
        if form.is_valid():
            f = form.cleaned_data['family']
            s = form.cleaned_data['species']
            return render(request, 'thankyou.html', {})
    else: 
         form = ResearchForm() # an unbound form
    return render(request, "research.html", {'form':form})

research.html

...
<form action="/research/" method="get" name="researchform">
   {{ form.as_p}}
   <button>Submit</button>
</form>
...

网页上只显示按钮,而不是select应呈现的ChoiceField标记。

编辑:

我将views.py编辑为:

def research(request):
    form = ResearchForm(request.GET)
    if form.is_valid():
        return render(request, 'thankyou.html', {})
    else: 
        form = ResearchForm()
        return render(request, 'research.html', {'form':form})

编辑2:

urls.py

urlpatterns = patterns('',
    url(r'^admin/', include(admin.site.urls)),
    url(r'^', include('cms.urls')),
)

if settings.DEBUG:
    urlpatterns = patterns('',
        (r'^' + settings.MEDIA_URL.lstrip('/'), include('appmedia.urls')),
    ) + urlpatterns

2 个答案:

答案 0 :(得分:2)

首次渲染页面时,将调用第一个条件:

if request.method == 'GET':

因为表单无效,所以它永远不会在任何地方传递,因此form变量为空。

而不是GET,两个地方都应该有POST

if request.method == 'POST': 
    form = ResearchForm(request.POST)

答案 1 :(得分:0)

您不应该检查方法,而只检查表单的有效性。类似的东西:

def research(request):
    form = ResearchForm(request.GET)
    if form.is_valid():
        f = form.cleaned_data['family']
        s = form.cleaned_data['species']
        return render(request, 'thankyou.html', {})
    else: 
        form = ResearchForm() # an unbound form
        return render(request, "research.html", {'form':form})

这样,如果GET请求包含有效的表单数据,则会显示感谢页面,如果没有,则会显示表单。