Django form does not appear

爱⌒轻易说出口 提交于 2019-12-23 05:35:09

问题


I'm working with building a webpage with a form using Django's Form class. I've included some sample code snippets but my problem is that I've followed the Django docs and the tutorial in Djangobook but can't get my Form to actually display on the page.

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>
...

Only the button appears on the webpage, not the select tags that ChoiceField should render.

EDIT:

I edited my views.py to this:

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})

EDIT 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

回答1:


When you first render the page the first condition will be called:

if request.method == 'GET':

and because form is not valid, it never gets passed anywhere, so the form variable is empty.

Instead of GET there should be POST in both places.

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



回答2:


You should not check the method, but only the validity of the form. Something like:

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})

That way, if the GET request contains valid form data the thank-you page is displayed, and if not, the form is rendered.



来源:https://stackoverflow.com/questions/21391510/django-form-does-not-appear

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!