【问题标题】:How to replace url paramater dynamically in html page with django?如何用django在html页面中动态替换url参数?
【发布时间】:2017-11-06 03:37:21
【问题描述】:

基本上,我有一个模板,它有一个搜索表单和一个表格来显示结果。如果单击标题列,则可以对结果进行排序。 我在搜索表单中使用get 方法并通过获取最后一个url对表格的结果进行排序。

views.py

if sort_by == "desc":
    order_by = order_by
    sort_by = "asc"
else:
    sort_by = "desc"

url = request.META.get('HTTP_REFERER')
if (url != None):
    search_params = {}
    param = urlparse.urlparse(url)
    if (not 'search_button' in request.GET):
        get_request = re.split('&',param.query)
        for single_request in get_request:
            search_query = re.split('=',single_request)
            search_params[search_query[0]] = search_query[1]
        userlist = show_data(order_by,sort_by,search_params)
    else:
        userlist = show_data(order_by, sort_by, request.GET)

def show_data(order_by, sort_by, get_data):
    //the function get the value from db
    return row

模板.py

<table id="user-table">
    <tr>
         <th><a href="?order_by=userId&sort={{sort}}">User id</a></th>
         <th><a href="?order_by=userName&sort={{sort}}">Name</a></th>
         <th><a href="order_by=userAddr&sort={{sort}}">Address</a></th>
    </tr>
    <tbody>
{% for item in table_data %}
<tr>
    <td>{{ item.userId|default_if_none:"" }}</td>
    <td>{{ item.userName|default_if_none:"" }}</td>
    <td>{{ item.userAddr|default_if_none:"" }}</td>
</tr>

能够过滤和表格结果的搜索表单可以对数据进行排序。 这是示例网址:

如果点击了搜索按钮

http://localhost:8080/userlist/?userId=&userName=Jane&userAddr=&search_button=search

如果点击了列标题

http://localhost:8080/userlist/?order_by=userAddr&sort=asc

但是,由于 url 已更改且 search_param 没有得到 userName=Jane,因此无法再次进行排序

如果点击列标题,是否可以在下面的html页面中动态替换url参数?

http://localhost:8080/userlist/?userId=&userName=Jane&userAddr=&search_button=search&order_by=userAddr&sort=desc

提前谢谢你。任何建议都会考虑。

【问题讨论】:

    标签: django django-models django-forms django-templates django-views


    【解决方案1】:

    为什么不发送带有上下文的搜索内容。例如:

    假设您正在使用此视图来呈现结果:

    def some_view(request):
        # Do your search mechanism
        search_items = []
        for key, value in search_params.items():
             search_items.append('{}={}'.format(key, value))
    
        return render(request, 'myapp/index.html', {
        'user_list': userList,
        'search_param': '&'.join(search_items)
        }, content_type='application/xhtml+xml')
    

    在 HTML 中:

    <tr>
             <th><a href="?order_by=userId&sort={{sort}}&{{search_param}}&search_button=search">User id</a></th>
             <th><a href="?order_by=userName&sort={{sort}}&{{search_param}}&search_button=search">Name</a></th>
             <th><a href="order_by=userAddr&sort={{sort}}&{{search_param}}&search_button=search">Address</a></th>
    </tr>
    

    【讨论】:

      猜你喜欢
      • 2016-07-10
      • 2012-07-08
      • 2020-07-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-01
      • 1970-01-01
      • 2022-08-09
      相关资源
      最近更新 更多