当页面在django中刷新时,下拉菜单显示所选项目

时间:2014-02-16 22:42:29

标签: javascript jquery python html django

有没有办法让它成为当使用html下拉表单并且页面在django / python中刷新以使下拉菜单保留在所选过滤器上时?这是我目前的表格:

<form name="portfolio_filter" action="" method="get"> 
    <select class="orderby pull-right push-bottom" name="orderby" onChange="location = this.options[this.selectedIndex].value">
            <option value="">Filter for Products</option>
            <option value="{% url 'products:portfolio_filtered' '-our_rating' %}">Best Match</option>
            <option value="{% url 'products:portfolio_filtered' '-created' %}">Newest</option>
            <option value="{% url 'products:portfolio_filtered' 'title' %}">Sort A-Z</option>
            <option value="{% url 'products:portfolio_filtered' '-title' %}">Sort Z-A</option>
            <option value="{% url 'products:portfolio_filtered' '-unit_price' %}">Price: Highest to Lowest</option>
            <option value="{% url 'products:portfolio_filtered' 'sale_price' %}">Price: Lowest to Highest</option>
    </select>
</form>

表单效果很好,让我进入产品组合列表页面并按标题,评级等对其进行过滤。但每次执行此操作时,下拉默认为第一项:

<option value="">Filter for Products</option>

我希望它留在所选项目上。因此,如果我进入“评级”,那么它将显示页面重新加载时下拉列表中的第一个“评级”过滤器。我相信html是<selected="selected">或类似的东西,我想知道我是否会填充Javascript或JQuery?但我不知道怎么样?

由于

2 个答案:

答案 0 :(得分:0)

最好通过ajax加载页面,这样形式保持不变只有另一部分将被重新加载。

或者

如果必须重新加载页面,则使用django-sessions或django cache并将会话或缓存键设置为所选值,然后再刷新并将其恢复并发送到前端。

答案 1 :(得分:0)

我暂时使用Django做到了这一点。我做了一个词典:

portfolio_filters = {'title': 'Sort A-Z',
                    '-our_rating': 'Best Match', 
                    '-created': 'Newest',
                    'sale_price': 'Price Lowest to Highest'}
然后把那个Dict送进我的Paginated视图:

def portfolio_filtered(request, slug):

template_name = 'products/shop-full-width.html'
products_list = Product.objects.order_by(slug)
paginator = Paginator(products_list, 12)
ideas = Idea.objects.all()

try:
    page = int(request.GET.get('page', '1'))
except:
    page = 1

try:
    products = paginator.page(page)
except(EmptyPage, InvalidPage):
    products = paginator.page(paginator.num_pages)

return render_to_response(template_name,
    {'ideas': ideas, 'products': products,
    'portfolio_filters': portfolio_filters, 'slug': slug},
    context_instance=RequestContext(request))

然后在我的模板中,我使用了For Loop / If语句:

<select class="orderby pull-right push-bottom" name="orderby" onChange="location = this.options[this.selectedIndex].value">
        <option value="">Filter for Products</option>
        {% for k, v in portfolio_filters.items %}
            {% if k == slug %}
                <option value="{% url 'products:portfolio_filtered_two' %}/{{ k }}/" selected="selected">{{ v }}</option>
            {% else %}
                <option value="{% url 'products:portfolio_filtered_two' %}{{ k }}/">{{ v }}</option>
            {% endif %}
        {% endfor %}
</select>

如果重要的话,这是我的网址:

url(r'^portfolio/filtered/$', views.portfolio_filtered, name='portfolio_filtered_two'),