Python django.http.request.QueryDict() Examples

The following are 30 code examples of django.http.request.QueryDict(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.http.request , or try the search function .
Example #1
Source File: test_widgets.py    From cadasta-platform with GNU Affero General Public License v3.0 8 votes vote down vote up
def test_value_from_datadict(self):
        formset = formset_factory(ContactsForm)
        widget = widgets.ContactsWidget(attrs={'formset': formset})
        data = {
            'contacts-TOTAL_FORMS': '2',
            'contacts-INITIAL_FORMS': '1',
            'contacts-MIN_NUM_FORMS': '0',
            'contacts-MAX_NUM_FORMS': '1000',
            'contacts-0-name': 'Ringo',
            'contacts-0-email': 'ringo@beatles.uk',
            'contacts-0-tel': '555-555',
            'contacts-1-name': '',
            'contacts-1-email': '',
            'contacts-1-tel': ''
        }
        q_dict = QueryDict('', mutable=True)
        q_dict.update(data)
        value = widget.value_from_datadict(q_dict, {}, 'contacts')
        assert isinstance(value, formset) 
Example #2
Source File: test_forms_search_courses.py    From richie with MIT License 6 votes vote down vote up
def test_forms_courses_empty_querystring(self, *_):
        """The empty query string should be a valid search form."""
        form = CourseSearchForm(data=QueryDict())
        self.assertTrue(form.is_valid())

        self.assertEqual(
            form.cleaned_data,
            {
                "availability": [],
                "languages": [],
                "levels": [],
                "levels_include": "",
                "limit": None,
                "new": [],
                "offset": None,
                "organizations": [],
                "organizations_include": "",
                "persons": [],
                "persons_include": "",
                "query": "",
                "scope": "",
                "subjects": [],
                "subjects_include": "",
            },
        ) 
Example #3
Source File: test_forms_search_courses.py    From richie with MIT License 6 votes vote down vote up
def test_forms_courses_query_between_3_and_100_characters_long(self, *_):
        """The `query` param should be between 3 and 100 characters long."""
        form = CourseSearchForm(data=QueryDict(query_string="query=aa"))
        self.assertFalse(form.is_valid())
        self.assertEqual(
            form.errors,
            {"query": ["Ensure this value has at least 3 characters (it has 2)."]},
        )

        form = CourseSearchForm(data=QueryDict(query_string="query=aaa"))
        self.assertTrue(form.is_valid())

        form = CourseSearchForm(
            data=QueryDict(query_string="query={:s}".format("a" * 100))
        )
        self.assertTrue(form.is_valid())

        form = CourseSearchForm(
            data=QueryDict(query_string="query={:s}".format("a" * 101))
        )
        self.assertFalse(form.is_valid())
        self.assertEqual(
            form.errors,
            {"query": ["Ensure this value has at most 100 characters (it has 101)."]},
        ) 
Example #4
Source File: pages.py    From wagtail with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get(self, request, *args, **kwargs):
        page = self.get_page()

        post_data, timestamp = self.request.session.get(self.session_key,
                                                        (None, None))
        if not isinstance(post_data, str):
            post_data = ''
        form = self.get_form(page, QueryDict(post_data))

        if not form.is_valid():
            return self.error_response(page)

        form.save(commit=False)

        try:
            preview_mode = request.GET.get('mode', page.default_preview_mode)
        except IndexError:
            raise PermissionDenied

        return page.make_preview_request(request, preview_mode) 
Example #5
Source File: test_select_county_view.py    From intake with MIT License 5 votes vote down vote up
def test_county_select_persists_after_session_update(self):
        response = self.client.fill_form(
            reverse('intake-apply'), counties=['alameda', 'contracosta'])
        request = response.wsgi_request
        qdict = QueryDict('', mutable=True)
        qdict.setlist('hello', ['world'])
        utils.save_form_data_to_session(
            request, ApplicantFormViewBase.session_key, qdict)
        form_data = self.client.session.get(ApplicantFormViewBase.session_key)
        self.assertListEqual(['alameda', 'contracosta'], form_data['counties']) 
Example #6
Source File: test_forms_search_items.py    From richie with MIT License 5 votes vote down vote up
def test_forms_items_build_es_query_search_all(self, *_):
        """
        Happy path: a match all query is returned
        """
        form = ItemSearchForm(data=QueryDict(query_string="limit=11&offset=4"))
        self.assertTrue(form.is_valid())
        self.assertEqual(form.build_es_query(), (11, 4, {"query": {"match_all": {}}})) 
Example #7
Source File: test_forms_search_courses.py    From richie with MIT License 5 votes vote down vote up
def test_forms_courses_limit_integer(self, *_):
        """The `limit` param should be an integer."""
        form = CourseSearchForm(data=QueryDict(query_string="limit=a"))
        self.assertFalse(form.is_valid())
        self.assertEqual(form.errors, {"limit": ["Enter a whole number."]})

        form = CourseSearchForm(data=QueryDict(query_string="limit=1"))
        self.assertTrue(form.is_valid()) 
Example #8
Source File: test_forms_search_courses.py    From richie with MIT License 5 votes vote down vote up
def test_forms_courses_offset_greater_than_0(self, *_):
        """The `offset` param should be greater than 0."""
        form = CourseSearchForm(data=QueryDict(query_string="offset=-1"))
        self.assertFalse(form.is_valid())
        self.assertEqual(
            form.errors,
            {"offset": ["Ensure this value is greater than or equal to 0."]},
        ) 
Example #9
Source File: test_forms_search_courses.py    From richie with MIT License 5 votes vote down vote up
def test_forms_courses_offset_integer(self, *_):
        """The `offset` param should be an integer."""
        form = CourseSearchForm(data=QueryDict(query_string="offset=a"))
        self.assertFalse(form.is_valid())
        self.assertEqual(form.errors, {"offset": ["Enter a whole number."]})

        form = CourseSearchForm(data=QueryDict(query_string="offset=1"))
        self.assertTrue(form.is_valid()) 
Example #10
Source File: test_forms_search_courses.py    From richie with MIT License 5 votes vote down vote up
def test_forms_courses_build_es_query_search_by_match_text(self, *_):
        """
        Happy path: build a query that filters courses by matching text
        """
        form = CourseSearchForm(
            data=QueryDict(query_string="limit=2&offset=20&query=some%20phrase%20terms")
        )
        self.assertTrue(form.is_valid())
        self.assertEqual(
            form.build_es_query()[2],
            {
                "bool": {
                    "must": [
                        {
                            "multi_match": {
                                "analyzer": "english",
                                "fields": [
                                    "description.*",
                                    "title.*",
                                    "categories_names.*^0.05",
                                    "organizations_names.*^0.05",
                                    "persons_names.*^0.05",
                                ],
                                "query": "some phrase terms",
                                "type": "cross_fields",
                            }
                        }
                    ]
                }
            },
        ) 
Example #11
Source File: utils.py    From intake with MIT License 5 votes vote down vote up
def get_form_data_from_session(request, session_key):
    """Gets a dictionary from the session based on a key
        and converts each key, list pair into a mutable QueryDict
        so that it can be processed by a form as if it were post data
    """
    raw_dict = request.session.get(session_key, {})
    qdict = QueryDict('', mutable=True)
    for key, items in raw_dict.items():
        if not isinstance(items, list):
            items = [items]
        qdict.setlist(key, items)
    return qdict 
Example #12
Source File: test_forms_search_items.py    From richie with MIT License 5 votes vote down vote up
def test_forms_items_build_es_query_by_match_text_with_kind(self, *_):
        """
        Make sure the generated query filters the items by kind when one is provided
        as argument.
        """
        form = ItemSearchForm(
            data=QueryDict(query_string="limit=20&offset=2&query=some%20phrase%20terms")
        )
        self.assertTrue(form.is_valid())
        self.assertEqual(
            form.build_es_query(kind="subjects"),
            (
                20,
                2,
                {
                    "query": {
                        "bool": {
                            "must": [
                                {"term": {"kind": "subjects"}},
                                {
                                    "multi_match": {
                                        "analyzer": "english",
                                        "fields": ["title.*"],
                                        "query": "some phrase " "terms",
                                    }
                                },
                            ]
                        }
                    }
                },
            ),
        ) 
Example #13
Source File: test_edit_form_service.py    From intake with MIT License 5 votes vote down vote up
def dict_to_querydict(dict_data):
    qdict = QueryDict('', mutable=True)
    for key, value in dict_data.items():
        if isinstance(value, list):
            qdict.setlist(key, value)
        else:
            qdict[key] = value
    return qdict 
Example #14
Source File: factory.py    From Wooey with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def multi_value_from_datadict(func):
    def value_from_datadict(data, files, name):
        return [func(QueryDict('{name}={value}'.format(name=name, value=six.moves.urllib.parse.quote(i))), files, name) for i in data.getlist(name)]
    return value_from_datadict 
Example #15
Source File: tests.py    From django-admin-easy with MIT License 5 votes vote down vote up
def test_response_normal(self):
        from django.contrib.messages.storage import default_storage

        request = HttpRequest()
        request.GET = QueryDict('test=asd')
        request.session = SessionStore('asd')
        request._messages = default_storage(request)

        response = easy.action_response(request, 'Some message')

        self.assertEqual(len(request._messages._queued_messages), 1)
        self.assertEqual(response.status_code, 302)
        self.assertEqual(response['Location'], './?test=asd') 
Example #16
Source File: tests.py    From django-admin-easy with MIT License 5 votes vote down vote up
def test_response_without_querystring(self):
        from django.contrib.messages.storage import default_storage

        request = HttpRequest()
        request.GET = QueryDict('test=asd')
        request.session = SessionStore('asd')
        request._messages = default_storage(request)

        response = easy.action_response(request, 'Some message', keep_querystring=False)

        self.assertEqual(len(request._messages._queued_messages), 1)
        self.assertEqual(response.status_code, 302)
        self.assertEqual(response['Location'], '.') 
Example #17
Source File: tests.py    From django-admin-easy with MIT License 5 votes vote down vote up
def test_response_whitout_message(self):
        from django.contrib.messages.storage import default_storage

        request = HttpRequest()
        request.GET = QueryDict('test=asd')
        request.session = SessionStore('asd')
        request._messages = default_storage(request)

        response = easy.action_response(request)
        self.assertEqual(len(request._messages._queued_messages), 0)

        self.assertEqual(response.status_code, 302)
        self.assertEqual(response['Location'], './?test=asd') 
Example #18
Source File: tests.py    From django-admin-easy with MIT License 5 votes vote down vote up
def test_response_whitout_message_and_querystring(self):
        from django.contrib.messages.storage import default_storage

        request = HttpRequest()
        request.GET = QueryDict('test=asd')
        request.session = SessionStore('asd')
        request._messages = default_storage(request)

        response = easy.action_response(request, keep_querystring=False)

        self.assertEqual(len(request._messages._queued_messages), 0)
        self.assertEqual(response.status_code, 302)
        self.assertEqual(response['Location'], '.') 
Example #19
Source File: test_device.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_contains_mac_addresses_field_and_converts_non_querydict(self):
        form = DeviceWithMACsForm(data={})
        self.assertThat(form.fields, Contains("mac_addresses"))
        self.assertIsInstance(form.data, QueryDict) 
Example #20
Source File: test_forms_search_items.py    From richie with MIT License 5 votes vote down vote up
def test_forms_items_empty_querystring(self, *_):
        """The empty query string should be a valid search form."""
        form = ItemSearchForm(data=QueryDict())
        self.assertTrue(form.is_valid())
        self.assertEqual(
            form.cleaned_data, {"limit": None, "offset": None, "query": "", "scope": ""}
        ) 
Example #21
Source File: views.py    From aswan with GNU Lesser General Public License v2.1 5 votes vote down vote up
def delete(self, request):
        request.DELETE = QueryDict(request.body)
        entity_id = request.DELETE.get('entity_id')
        if not entity_id:
            return self.render_json_response({
                'state': False,
                'error': 'entity_id is required!'
            }, status=400)
        group = UriGroupPermission.objects.get_by_id(entity_id)
        group.delete()
        return self.render_json_response({'state': True}) 
Example #22
Source File: search.py    From palanaeum with GNU Affero General Public License v3.0 5 votes vote down vote up
def init_from_get_params(self, get_params: QueryDict) -> bool:
        """
        Initialize this filter using data passed in GET request.
        Return bool indicating if this search filter is used.
        """
        raise NotImplementedError 
Example #23
Source File: search.py    From palanaeum with GNU Affero General Public License v3.0 5 votes vote down vote up
def init_from_get_params(self, get_params: QueryDict):
        self.search_phrase = get_params.get(self.GET_PARAM_NAME, '').strip()

        if not self.search_phrase:
            return False

        for quoted_text in self.QUOTE_REGEXP.findall(self.search_phrase):
            self.exact_search_tokens.append(quoted_text[1])

        for word in self.QUOTE_REGEXP.sub('', self.search_phrase).split(' '):
            self.search_tokens.append(word)

        return True 
Example #24
Source File: search.py    From palanaeum with GNU Affero General Public License v3.0 5 votes vote down vote up
def init_from_get_params(self, get_params: QueryDict):
        try:
            date_from_str = get_params.get(self.GET_DATE_FROM, None)
            date_to_str = get_params.get(self.GET_DATE_TO, None)
            self.date_from = datetime.strptime(date_from_str, '%Y-%m-%d')
            self.date_to = datetime.strptime(date_to_str, '%Y-%m-%d')
        except (ValueError, TypeError):
            return False
        else:
            self._active = True

        return True 
Example #25
Source File: search.py    From palanaeum with GNU Affero General Public License v3.0 5 votes vote down vote up
def init_from_get_params(self, get_params: QueryDict) -> bool:
        tags = {tag.lower() for tag in get_params.getlist(self.GET_TAG_SEARCH)}
        self.tags = Tag.objects.annotate(name_lower=Lower('name')).filter(name_lower__in=tags)
        return bool(self.tags) 
Example #26
Source File: test_common_templatetags.py    From byro with Apache License 2.0 5 votes vote down vote up
def __init__(self, get):
        self.GET = QueryDict(get) 
Example #27
Source File: v1.py    From lexpredict-contraxsuite with GNU Affero General Public License v3.0 5 votes vote down vote up
def send_clusters_to_project(self, request, **kwargs):
        """
        Send clusters to another Project\n
            Params:
                - cluster_ids: list[int]
                - project_id: int
        """
        project = self.get_object()

        # via API
        if isinstance(request.data, QueryDict):
            cluster_ids = [int(i) for i in request.data.getlist('cluster_ids')]
        # via swagger
        else:
            cluster_ids = request.data['cluster_ids']

        project_clustering = project.projectclustering_set.last()
        if not project_clustering:
            raise APIException('Project Clustering object not found')
        reassigned_cluster_ids = project_clustering.metadata.get('reassigned_cluster_ids', [])
        already_reassigned_clusters = set(cluster_ids) & set(reassigned_cluster_ids)
        if already_reassigned_clusters:
            raise APIException('Cluster(s) id=({}) is/are already reassigned to another project'
                               .format(', '.join(str(i) for i in already_reassigned_clusters)))

        new_project_id = int(request.data['project_id'])
        call_task(
            ReassignProjectClusterDocuments,
            project_clustering_id=project_clustering.id,
            cluster_ids=cluster_ids,
            project_id=project.id,
            new_project_id=new_project_id,
            user_id=request.user.id)

        return Response('OK') 
Example #28
Source File: views.py    From aswan with GNU Lesser General Public License v2.1 5 votes vote down vote up
def delete(self, request):
        request.DELETE = QueryDict(request.body)
        entity_id = request.DELETE.get('entity_id')
        if not entity_id:
            return self.render_json_response({
                'state': False,
                'error': 'entity_id is required!'
            }, status=400)
        group = GroupPermission.objects.get_by_id(entity_id)
        group.delete()
        return self.render_json_response({'state': True}) 
Example #29
Source File: test_forms_search_items.py    From richie with MIT License 5 votes vote down vote up
def test_forms_items_limit_greater_than_1(self, *_):
        """The `limit` param should be greater than 1."""
        form = ItemSearchForm(data=QueryDict(query_string="limit=0"))
        self.assertFalse(form.is_valid())
        self.assertEqual(
            form.errors, {"limit": ["Ensure this value is greater than or equal to 1."]}
        ) 
Example #30
Source File: test_forms_search_items.py    From richie with MIT License 5 votes vote down vote up
def test_forms_items_limit_integer(self, *_):
        """The `limit` param should be an integer."""
        form = ItemSearchForm(data=QueryDict(query_string="limit=a"))
        self.assertFalse(form.is_valid())
        self.assertEqual(form.errors, {"limit": ["Enter a whole number."]})

        form = ItemSearchForm(data=QueryDict(query_string="limit=1"))
        self.assertTrue(form.is_valid())