gpt4 book ai didi

python - 在 Django 上显示一个空的 GET 表单而不引发任何错误

转载 作者:太空宇宙 更新时间:2023-11-04 01:21:49 25 4
gpt4 key购买 nike

我正在尝试在我的项目中设置一个显示搜索表单的主页(使用 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)

这是相对 View :

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

最佳答案

您只需添加或None,如下所示:

form = SearchForm(request.GET or None)

关于python - 在 Django 上显示一个空的 GET 表单而不引发任何错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20718443/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com