问题产生原因:接口平台中,某一个项目接口比较多,根据项目搜索完成后,编辑其中某一条用例,提交后返回列表页(所有的搜索条件都没有了),这样的操作就会很烦,每次有很多重复的步骤搜索--编辑-提交-搜索-运行,这样的步骤周而复始,使用很不方便,那么能不能在提交之后返回之前的搜索页面呢?

有,上代码


@login_required
def api_case_search(request):
"""
apicase 搜索
:param request:
:return:
"""
project = Project.objects.all().filter(flag=1)

page = request.GET.get('page')
search_data = {}
project_id = request.GET.get('project_id')
api_name = request.GET.get('api_name')
api_url = request.GET.get('api_url')
if project_id:
search_data['project_id'] = int(project_id)
if api_name:
search_data['api_name'] = api_name
if api_url:
search_data['api_url'] = api_url
search_data['flag'] = 1
  # 在搜索的时候,就索取当前的URL,然后返回列表页
get_all_path = request.get_full_path()
# 如果获取到了,使用?进行切片,要后半部分的参数,然后需要吧&转成-,因为调试发现&会被转义
if get_all_path:
get_all_path = str(get_all_path).split('?')[1]
get_all_path = get_all_path.replace("&", "-")
log.info("get_all_path:%s" % get_all_path)

api_case = ApiCase.objects.filter(**search_data)

paginator = Paginator(api_case, 20)

try:
contacts = paginator.page(page)
except PageNotAnInteger:
# 如果请求的页数不是整数,返回第一页。
contacts = paginator.page(1)
except EmptyPage:
# 如果请求的页数不在合法的页数范围内,返回结果的最后一页。
contacts = paginator.page(paginator.num_pages)
return render(request, "api/apiIndex.html", locals())


在列表页,建立一个不展示的input框,搜索后赋值给这个input

Django 列表搜索后,进行数据编辑,保存后返回搜索前的页面 && 多条件搜索_重定向


在编辑的时候,将input的内容加入到编辑的URL中,使用nexturl承接

 Django 列表搜索后,进行数据编辑,保存后返回搜索前的页面 && 多条件搜索_html_02


 编辑的时候,需要处理获取到的URL,


@login_required
def api_case_edit(request):
"""
apiccase 修改
:param request:
:return: 如果修改成功,保存后重定向到之前的搜索页面
"""
project = Project.objects.all().filter(flag=1)
if request.method == "GET":
api_case_id = int(request.GET.get('id'))
# 在进入编辑页的时候,定义一个全局变量nexturl
global nexturl
nexturl = request.GET.get('nexturl')
log.info("api_case_edit.nexturl:%s" % nexturl)
# nexturl 可能为空,不为空,我们要将URL中的-替换成&,然后拼接上路由 
if nexturl is None or nexturl == ' ':
pass
else:
nexturl = str(nexturl).replace("-", "&")
nexturl = '/apiCase/apiCaseSearch/?' + nexturl
log.info("new api_case_edit.nexturl:%s" % nexturl)
api_case = ApiCase.objects.get(id=api_case_id)
return render(request, 'api/apiEdit.html', locals())
elif request.method == "POST":
user = request.session.get('user_name')
body = request.POST.dict()
data = public.filter_csrf(body)
project = data['project_id']
project_id = Project.objects.get(id=project)
data['project_id'] = project_id
data['create_user'] = user
api_url = data['api_url']
api_case_id = data['id']
try:
ApiCase.objects.filter(id=api_case_id).update(**data)
print(nexturl)
# 如果URL的长度超过24,我们认为跳转连接符合搜索的连接,就做重定向,否则就返回列表页 
if len(nexturl) > 24:
return HttpResponseRedirect(nexturl)
return redirect(reverse("apiCase:apiCaseIndex"))
except Exception as e:
log.info("api_case_add")
error_msg = str(e)
return render(request, "api/apiEdit.html", locals())