我想在我的页面上有一些搜索框,我的相关代码如下所示,我的问题是为什么当我刷新页面时,if 子句:"如果request.method=='GET':"在没有我单击任何按钮的情况下执行?
def allstocks_view(request):
if request.method=='GET':
question_set =Stocks.objects.all().filter(confirm=_('approved') )
name=request.GET.get('namesearch')
number=request.GET.get('numbersearch')
brand=request.GET.get('brandsearch')
if name is not None :
question_set = question_set.filter(name__icontains = name)
if number is not None :
question_set = question_set.filter(number__icontains = number)
if request.GET.get("brandsearch"):
question_set = question_set.filter(brand__icontains = brand)
print(">>>>>>>>>>>>>>>>>>>>")
print(question_set)
模板:
<form method="get">
{% csrf_token %}
<div class="">
<label for="namesearch">Name</label>
<input type="text" name="namesearch" >
<label for="numbersearch"> Number</label>
<input type="text" name="numbersearch" >
<label for="brandsearch"> Brand</label>
<input type="text" name="brandsearch" >
<label for="brandsearch"> City</label>
<input type="text" name="citysearch" >
<input type="submit" name="search" value="Search">
</div>
</form>
刷新
页面是一个GET
请求,除非您的最后一个操作是POST
请求,因此每次都会执行。您可以做的是将表单作为request.method == 'POST'
块中的帖子和句柄。如果您想继续使用GET
,另一种选择是让您的视图采用可选参数(例如 search=None
(并相应地设置您的 URL。然后,在您的视图中,您可以检查search
是否存在而不是request.method == 'GET'
。