Django为什么要求。方法==' GET'刷新页面时

时间:2018-03-08 16:25:11

标签: django get refresh

我想在我的页面上有一些搜索框,我的相关代码如下所示,我的问题是为什么当我刷新页面时if条款:" 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>

1 个答案:

答案 0 :(得分:1)

刷新页面是GET请求,除非您的上一个操作是POST请求,因此每次都会执行。您可以做的是将表单作为帖子并在request.method == 'POST'块中处理。如果您希望继续使用GET,另一个选项是让您的视图采用search=None等可选参数并相应地设置您的网址。然后,在您的视图中,您可以检查search是否存在,而不是request.method == 'GET'