在生成URL时,需要读取当前URL中的参数并构造URL。例如:
-
当前URL
http://127.0.0.1:8000/customer/list/?keyword=xinchen&page=8
-
构造编辑页面URL
http://127.0.0.1:8000/customer/edit/1/?_filter=keyword%3Dxinchen%26page%3D8
param = request.GET.urlencode() # 获取?后面的值 new_query_dict = QueryDict(mutable=True) # 创建一个对象,设置可修改 new_query_dict['_filter'] = param new_query_dict.urlencode() # 内部自动实现转义
-
跳转回来时
http://127.0.0.1:8000/customer/list/?keyword=xinchen&page=8
def policy_edit(request, pk): ... base_url = reverse(name, args=args, kwargs=kwargs) param_url = request.GET.get('_filter') url = "{}?{}".format(base_url,param_url) return redirect(url)
实操分享:
permission.py
@register.simple_tag()
def edit_permission(request, name, *args, **kwargs):
# 3.判断是否具有权限
# 4.无权限,返回空
if not check_permission(request, name):
return ""
# 5.有权限,通过"name"反向生成url
url = reverse(name, args=args, kwargs=kwargs)
# 根据当前用户请求获取GET参数
param = request.GET.urlencode() # name=1&age=3
if param:
new_query_dict = QueryDict(mutable=True) # 创建一个对象,设置可修改
new_query_dict['_filter'] = param # <QueryDict: {'_filter': ['name=1&age=3']}>
filter_string = new_query_dict.urlencode()
tpl = """<a href="{}?{}" class="btn btn-primary btn-xs">编辑</a>""".format(url, filter_string)
return mark_safe(tpl)
tpl = """<a href="{}" class="btn btn-primary btn-xs">编辑</a>""".format(url)
return mark_safe(tpl)
customer.py
def customer_edit(request, pk):
instance = models.Customer.objects.filter(id=pk, active=1).first()
if request.method == "GET":
form = CustomerEditModelForm(request, instance=instance)
return render(request, 'form2.html', {'form': form})
form = CustomerEditModelForm(request, instance=instance, data=request.POST)
if not form.is_valid():
return render(request, 'form2.html', {'form': form})
form.save()
filter_string = request.GET.get('_filter')
if not filter_string:
return redirect('/customer/list/')
return redirect('/customer/list/?{}'.format(filter_string))