显示空的GET表单而不会在Django上引发任何错误

时间:2013-12-21 11:20:48

标签: python django django-forms

我正在尝试将主页设置为显示搜索表单的项目(使用GET方法)。 问题是,由于默认请求方法是GET,因此在加载页面时它会引发错误。当然我可以将表单的方法更改为POST但这不是正确的方法,所以我想知道是否有任何条件我可以设置以避免此问题并仍然能够检查任何错误。

我正在处理Django 1.5Python 2.7

如果表单类:

class Search(forms.Form):
    middleschool = 'MS'
    highschool = 'HS'
    university = 'U'
    blank = '-'

    school_choices = ((middleschool, 'Middle School'),
                      (highschool, 'High school'),
                      (university, 'University'),
                      (blank, 'Not defined'),)

    title = forms.CharField(label='Keyworld')
    subject = forms.ModelChoiceField(queryset=Subject.objects.order_by('?'),
                  required=False, label='Whitch subject you want to search?')
    school = forms.ChoiceField(choices = school_choices, required=False, 
                 label='What level of material are you searching?') 
    price = forms.BooleanField(required=False)

这是相对观点:

def home(request):
    if request.method == 'GET':
        form = Search(request.GET)
        if form.is_valid():
            cd = form.cleaned_data
            ftitle = cd['title']
            fsubject = cd['subject']
            fschool = cd['school']
            fprice = cd['price']
            if fprice:
                forms = File.objects.filter(name__contains='ftitle', subject='fsubject', school='fschool', price = '0,0')
                return render(request, 'search.html', {'form': form})
            else:
                forms = File.objects.filter(name__contains='ftitle', subject='fsubject', school='fschool')
                return render(request, 'search.html', {'form': form})
    else:
        form = Search()
    return render(request, 'home.html', {'form': form})

这是HTML:

{% block content %}
<hr>
<div id='search'>
    {% if form.errors %}
    <p style="color: red;">
        Please correct the error{{ form.errors|pluralize }} below.
    </p>
    {% endif %}

    <form action="/search/" method="get">
        <div class="field">{{ form.title.errors }}<label for="keyworld">Keyworld:</label>{{ form.title }}</div>
        <div class="field"><label for="subject">Subject:</label>{{ form.subject }}</div>
        <div class="field"><label for="school">Level:</label>{{ form.school }}</div>
        <div class="field"><label for="price">Price yes or no:</label>{{ form.price }}</div>
        <input type="submit" value="Search">
        <input type="reset" value="Reset">
    </form>
</div>
<hr>
{% endblock %}

2 个答案:

答案 0 :(得分:2)

您只需添加or None,就像这样:

form = SearchForm(request.GET or None)

答案 1 :(得分:1)

您可以检查request.GET是否为空,而不是检查请求方法:

if request.GET:
    form = SearchForm(request.GET)