每次在表单中输入值时,我一直在尝试修复一个有重置特定值问题的表单。
我正在按照本教程关于如何在提交表单后突然停留特定值,
我收到此错误
Key 'Category' not found in <QueryDict: {}>
File "C:\o\mysite\pet\views.py" in WhiteBoardFinder
234. if request.GET['Category']:
File "C:\Python26\Lib\site-packages\django\utils\datastructures.py" in __getitem__
258. raise MultiValueDictKeyError("Key %r not found in %r" % (key, self))
我似乎无法理解这个问题,因为我的表单字段名为Category,而我正在使用django生成的表单。
我的views.py
def WhiteBoardFinder(request):
if request.GET['Category']:
request.session['Category'] = request.GET['Category']
category = request.GET['Category']
posts = WhiteBoard.objects.filter(Category=category)
form = WhiteBoardFinderForm(initial={'Category': request.session.get('Category')})
paginator = Paginator(posts, 1)
try: page = int(request.GET.get("page", '1'))
except ValueError: page = 1
try:
posts = paginator.page(page)
except (InvalidPage, EmptyPage):
posts = paginator.page(paginator.num_pages)
return render(request,"whiteboardfinder.html",{"posts":posts,'form':form},)
return render(request,"whiteboardfinder.html",{'form':WhiteBoardFinderForm()})
我的forms.py
class WhiteBoardFinderForm(forms.ModelForm):
class Meta:
model = WhiteBoard
fields = ('Category',)
我的whiteboardfinder.html
<form method="GET">
{{ form.as_p }}
<input type="submit" value="Search">
</form>
{% for post in posts.object_list %}
<div class="title">{{ post.name }}</div>
{% endfor %}
<!-- Next/Prev page links -->
{% if posts.object_list and posts.paginator.num_pages > 1 %}
<div class="pagination" style="margin-top: 20px; margin-left: -20px; ">
<span class="step-links">
{% if posts.has_previous %}
<a href= "?page={{ posts.previous_page_number }}">newer entries << </a>
{% endif %}
<span class="current">
Page {{ posts.number }} of {{ posts.paginator.num_pages }}
</span>
{% if posts.has_next %}
<a href="?page={{ posts.next_page_number }}"> >> older entries</a>
{% endif %}
</span>
</div>
{% endif %}
</div>
答案 0 :(得分:1)
if request.GET.get('Category'):
request.session['Category'] = request.GET['Category']
category = request.GET['Category']