Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Django-减少URL查询字符串长度_Django_Http_Django Forms_Query String - Fatal编程技术网

Django-减少URL查询字符串长度

Django-减少URL查询字符串长度,django,http,django-forms,query-string,Django,Http,Django Forms,Query String,我使用Django表单已经有一段时间了,但最近我不得不创建一个表单,用multipleechoicefield搜索数据。 由于URL必须在用户之间共享,因此表单将执行到服务器的GET操作,以将搜索参数保留在查询字符串中。 问题是,如果选中多个选项,URL的长度会增加太多。例如: http://www.mywebsite.com/search?source=1&source=2&source=3... 是否使用django表单获得如下url: http://www.mywebsi

我使用Django表单已经有一段时间了,但最近我不得不创建一个表单,用multipleechoicefield搜索数据。 由于URL必须在用户之间共享,因此表单将执行到服务器的GET操作,以将搜索参数保留在查询字符串中。 问题是,如果选中多个选项,URL的长度会增加太多。例如:

http://www.mywebsite.com/search?source=1&source=2&source=3...
是否使用django表单获得如下url:

http://www.mywebsite.com/search?source=1-2-3...
还是创建一个压缩查询字符串参数的令牌更好

然后使用该表单在ElasticSearch上进行搜索。我没有使用djangos模型


谢谢

模板视图
上覆盖
get
get\u context\u数据
可能会起作用。然后你可以有这样一个URL:
http://www.mywebsite.com/search?sources=1,2

class ItemListView(TemplateView):
    template_name = 'search.html'

    def get(self, request, *args, **kwargs):
        sources = self.request.GET.get('sources')
        self.sources = sources.split(',') if sources else None

        return super().get(request, *args, **kwargs)

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)

        if self.sources:
            context['search-results'] = self.get_search_results(
                self.sources,
            )

        return context

    def get_search_results(self, sources):
        """
        Retrieve items that have `sources`.
        """
        # ElasticSearch code here…

        data = {
            '1': 'Honen',
            '2': 'Oreth',
            '3': 'Vosty',
        }

        return [data[source_id] for source_id in sources]

现在,如果请求了
/search?sources=1,2
URL,模板上下文将包含
Honen
Oreth
,作为变量
搜索结果

我的答案是否有帮助?嗨,马特,我认为这是个好主意,但不适用于我的问题。我忘了提到我没有使用Django模型。数据来自ElasticSearch,因此没有涉及传统模型。我将更新问题。在这种情况下,您可以使用
TemplateView
并添加一个方法从ElasticSearch检索结果。我会更新我的答案。