Python django.http.QueryDict() Examples

The following are 30 code examples for showing how to use django.http.QueryDict(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module django.http , or try the search function .

Example 1
Project: Servo   Author: fpsw   File: order.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def list_orders(request):
    """
    orders/index
    """
    args = request.GET.copy()
    default = {'state': Order.STATE_QUEUED}

    if len(args) < 2:  # search form not submitted
        f = request.session.get("order_search_filter", default)
        args = QueryDict('', mutable=True)
        args.update(f)

    request.session['order_search_filter'] = args
    data = prepare_list_view(request, args)

    return render(request, "orders/index.html", data) 
Example 2
Project: GTDWeb   Author: lanbing510   File: views.py    License: GNU General Public License v2.0 6 votes vote down vote up
def redirect_to_login(next, login_url=None,
                      redirect_field_name=REDIRECT_FIELD_NAME):
    """
    Redirects the user to the login page, passing the given 'next' page
    """
    resolved_url = resolve_url(login_url or settings.LOGIN_URL)

    login_url_parts = list(urlparse(resolved_url))
    if redirect_field_name:
        querystring = QueryDict(login_url_parts[4], mutable=True)
        querystring[redirect_field_name] = next
        login_url_parts[4] = querystring.urlencode(safe='/')

    return HttpResponseRedirect(urlunparse(login_url_parts))


# 4 views for password reset:
# - password_reset sends the mail
# - password_reset_done shows a success message for the above
# - password_reset_confirm checks the link the user clicked and
#   prompts for a new password
# - password_reset_complete shows a success message for the above 
Example 3
Project: koku   Author: project-koku   File: tests_views.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_ocpcpuview_success(self, mock_handler):
        """Test OCP cpu view report."""
        mock_handler.return_value.execute_query.return_value = self.report_ocp_cpu
        params = {
            "group_by[node]": "*",
            "filter[resolution]": "monthly",
            "filter[time_scope_value]": "-1",
            "filter[time_scope_units]": "month",
        }
        user = User.objects.get(username=self.user_data["username"])

        django_request = HttpRequest()
        if not django_request.META.get("HTTP_HOST"):
            django_request.META["HTTP_HOST"] = "testhost"

        qd = QueryDict(mutable=True)
        qd.update(params)
        django_request.GET = qd
        request = Request(django_request)
        request.user = user

        response = OCPCpuView().get(request)
        self.assertIsInstance(response, Response)
        self.assertEqual(response.status_code, status.HTTP_200_OK) 
Example 4
Project: koku   Author: project-koku   File: tests_views.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_ocpmemview_success(self, mock_handler):
        """Test OCP memory view report."""
        mock_handler.return_value.execute_query.return_value = self.report_ocp_mem
        params = {
            "group_by[node]": "*",
            "filter[resolution]": "monthly",
            "filter[time_scope_value]": "-1",
            "filter[time_scope_units]": "month",
        }
        user = User.objects.get(username=self.user_data["username"])

        django_request = HttpRequest()
        if not django_request.META.get("HTTP_HOST"):
            django_request.META["HTTP_HOST"] = "testhost"

        qd = QueryDict(mutable=True)
        qd.update(params)
        django_request.GET = qd
        request = Request(django_request)
        request.user = user

        response = OCPMemoryView().get(request)
        self.assertIsInstance(response, Response)
        self.assertEqual(response.status_code, status.HTTP_200_OK) 
Example 5
Project: koku   Author: project-koku   File: tests_views.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_costview_with_units_success(self, mock_handler):
        """Test unit conversion succeeds in AzureCostView."""
        mock_handler.return_value.execute_query.return_value = self.report
        params = {
            "group_by[subscription_guid]": "*",
            "filter[resolution]": "monthly",
            "filter[time_scope_value]": "-1",
            "filter[time_scope_units]": "month",
            "units": "byte",
            "SERVER_NAME": "",
        }
        user = User.objects.get(username=self.user_data["username"])

        django_request = HttpRequest()
        qd = QueryDict(mutable=True)
        qd.update(params)
        django_request.GET = qd
        request = Request(django_request)
        request.user = user

        response = AzureCostView().get(request)
        self.assertIsInstance(response, Response) 
Example 6
Project: kobo-predict   Author: awemulya   File: views.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def export_menu(request, username, id_string):

    req = request.REQUEST
    export_type = req.get('type', None)
    if export_type:
        lang = req.get('lang', None)
        hierarchy_in_labels = req.get('hierarchy_in_labels')
        group_sep = req.get('group_sep', '/')

        q = QueryDict('', mutable=True)
        q['lang'] = req.get('lang')
        q['hierarchy_in_labels'] = req.get('hierarchy_in_labels')
        q['group_sep'] = req.get('group_sep', '/')

        if export_type == "xlsx":
            url = reverse('formpack_xlsx_export', args=(username, id_string))
            return redirect(url + '?' + q.urlencode())
        if export_type == "csv":
            url = reverse('formpack_csv_export', args=(username, id_string))
            return redirect(url + '?' + q.urlencode())

    context = build_export_context(request, username, id_string)
    return render(request, 'survey_report/export_menu.html', context) 
Example 7
Project: bioforum   Author: reBiocoder   File: views.py    License: MIT License 6 votes vote down vote up
def redirect_to_login(next, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME):
    """
    Redirect the user to the login page, passing the given 'next' page.
    """
    resolved_url = resolve_url(login_url or settings.LOGIN_URL)

    login_url_parts = list(urlparse(resolved_url))
    if redirect_field_name:
        querystring = QueryDict(login_url_parts[4], mutable=True)
        querystring[redirect_field_name] = next
        login_url_parts[4] = querystring.urlencode(safe='/')

    return HttpResponseRedirect(urlunparse(login_url_parts))


# 4 views for password reset:
# - password_reset sends the mail
# - password_reset_done shows a success message for the above
# - password_reset_confirm checks the link the user clicked and
#   prompts for a new password
# - password_reset_complete shows a success message for the above 
Example 8
Project: django-simple-pagination   Author: MicroPyramid   File: tests.py    License: MIT License 6 votes vote down vote up
def test_get_querystring_for_page(self):
        request = self
        request = HttpRequest()
        dict = {u"querystring_key": 1,
                u"key": 2,
                u"page": 3}
        qdict = QueryDict('', mutable=True)
        qdict.update(dict)
        request.GET = qdict
        val = get_querystring_for_page(request=request,
                                       page_number=1,
                                       querystring_key="key",
                                       default_number=1)
        self.assertTrue(bool(val))
        request.GET = {}
        val = get_querystring_for_page(request=request,
                                       page_number=1,
                                       querystring_key="key",
                                       default_number=1)
        self.assertFalse(bool(val)) 
Example 9
Project: django-simple-pagination   Author: MicroPyramid   File: tests.py    License: MIT License 6 votes vote down vote up
def test_get_querystring_for_page(self):
        request = self
        request = HttpRequest()
        dict = {u"querystring_key": 1,
                u"key": 2,
                u"page": 3}
        qdict = QueryDict('', mutable=True)
        qdict.update(dict)
        request.GET = qdict
        val = get_querystring_for_page(request=request,
                                       page_number=1,
                                       querystring_key="key",
                                       default_number=1)
        self.assertTrue(bool(val))
        request.GET = {}
        val = get_querystring_for_page(request=request,
                                       page_number=1,
                                       querystring_key="key",
                                       default_number=1)
        self.assertFalse(bool(val)) 
Example 10
Project: django-sudo   Author: mattrobenolt   File: views.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def redirect_to_sudo(next_url, sudo_url=None):
    """
    Redirects the user to the login page, passing the given 'next' page
    """
    if sudo_url is None:
        sudo_url = URL

    try:
        # django 1.10 and greater can't resolve the string 'sudo.views.sudo' to a URL
        # https://docs.djangoproject.com/en/1.10/releases/1.10/#removed-features-1-10
        sudo_url = import_string(sudo_url)
    except (ImportError, ImproperlyConfigured):
        pass  # wasn't a dotted path

    sudo_url_parts = list(urlparse(resolve_url(sudo_url)))

    querystring = QueryDict(sudo_url_parts[4], mutable=True)
    querystring[REDIRECT_FIELD_NAME] = next_url
    sudo_url_parts[4] = querystring.urlencode(safe="/")

    return HttpResponseRedirect(urlunparse(sudo_url_parts)) 
Example 11
Project: scale   Author: ngageoint   File: test_rest.py    License: Apache License 2.0 6 votes vote down vote up
def test_parse_bool_false(self):
        """Tests parsing a required bool parameter that is provided via GET."""
        request = MagicMock(Request)
        request.query_params = QueryDict('', mutable=True)
        request.query_params.update({
            'test1': 'FALSE',
            'test2': 'False',
            'test3': 'false',
            'test4': 'f',
            'test5': '0',
        })

        self.assertFalse(rest_util.parse_bool(request, 'test1'))
        self.assertFalse(rest_util.parse_bool(request, 'test2'))
        self.assertFalse(rest_util.parse_bool(request, 'test3'))
        self.assertFalse(rest_util.parse_bool(request, 'test4'))
        self.assertFalse(rest_util.parse_bool(request, 'test5')) 
Example 12
Project: Servo   Author: fpsw   File: account.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def orders(request):
    """
    This is basically like orders/index, but limited to the user
    First, filter by the provided search criteria,
    then check if we have a saved search filter
    then default to user id
    Always update saved search filter
    """
    args = request.GET.copy()
    default = {'state': Order.STATE_OPEN}

    if len(args) < 2:
        f = request.session.get("account_search_filter", default)
        args = QueryDict('', mutable=True)
        args.update(f)

    # On the profile page, filter by the user, no matter what
    args.update({'followed_by': request.user.pk})
    request.session['account_search_filter'] = args

    data = prepare_list_view(request, args)
    data['title'] = _("My Orders")

    del(data['form'].fields['assigned_to'])

    return render(request, "accounts/orders.html", data) 
Example 13
Project: django-accounting   Author: dulacp   File: url_tags.py    License: MIT License 5 votes vote down vote up
def render_tag(self, context, kwa):
        q = QueryDict('').copy()
        q.update(kwa)
        return q.urlencode() 
Example 14
Project: coursys   Author: sfu-fas   File: tests.py    License: GNU General Public License v3.0 5 votes vote down vote up
def test_advanced_search_3(self):
        client = Client()
        client.login_user('dzhao')
        this_sem = Semester.current()
        units = [r.unit for r in Role.objects_fresh.filter(person__userid='dzhao', role='GRAD')]

        gs = self.__make_test_grad()
        gs.gradstatus_set.all().delete()

        s1 = GradStatus(student=gs, status='COMP', start=this_sem.offset(-4))
        s1.save()
        s2 = GradStatus(student=gs, status='ACTI', start=this_sem.offset(-3))
        s2.save()
        s3 = GradStatus(student=gs, status='LEAV', start=this_sem.offset(2))
        s3.save()
        gs.update_status_fields()

        # test current-status searching
        form = SearchForm(QueryDict('student_status=ACTI&columns=person.emplid'))
        active_now = form.search_results(units)
        self.assertIn(gs, active_now)
        form = SearchForm(QueryDict('student_status=LEAV&columns=person.emplid'))
        leave_now = form.search_results(units)
        self.assertNotIn(gs, leave_now)

        # test status-as-of searching  -- DISABLED since we removed this from the form.
        #form = SearchForm(QueryDict('student_status=ACTI&status_asof=%s&columns=person.emplid' % (this_sem.offset(-4).name)))
        #active_past = form.search_results(units)
        #self.assertNotIn(gs, active_past)
        #form = SearchForm(QueryDict('student_status=COMP&status_asof=%s&columns=person.emplid' % (this_sem.offset(-4).name)))
        #applic_past = form.search_results(units)
        #self.assertIn(gs, applic_past)

        #form = SearchForm(QueryDict('student_status=ACTI&status_asof=%s&columns=person.emplid' % (this_sem.offset(3).name)))
        #active_later = form.search_results(units)
        #self.assertNotIn(gs, active_later)
        #form = SearchForm(QueryDict('student_status=LEAV&status_asof=%s&columns=person.emplid' % (this_sem.offset(3).name)))
        #leave_later = form.search_results(units)
        #self.assertIn(gs, leave_later) 
Example 15
Project: django-oidc-rp   Author: impak-finance   File: views.py    License: MIT License 5 votes vote down vote up
def provider_end_session_url(self):
        """ Returns the end-session URL. """
        q = QueryDict(mutable=True)
        q[oidc_rp_settings.PROVIDER_END_SESSION_REDIRECT_URI_PARAMETER] = \
            self.request.build_absolute_uri(settings.LOGOUT_REDIRECT_URL or '/')
        q[oidc_rp_settings.PROVIDER_END_SESSION_ID_TOKEN_PARAMETER] = \
            self.request.session['oidc_auth_id_token']
        return '{}?{}'.format(oidc_rp_settings.PROVIDER_END_SESSION_ENDPOINT, q.urlencode()) 
Example 16
Project: StormOnline   Author: stormsha   File: bookmark.py    License: Apache License 2.0 5 votes vote down vote up
def setup(self):
        BaseWidget.setup(self)

        bookmark = self.cleaned_data['bookmark']
        model = bookmark.content_type.model_class()
        data = QueryDict(bookmark.query)
        self.bookmark = bookmark

        if not self.title:
            self.title = smart_text(bookmark)

        req = self.make_get_request("", data.items())
        self.list_view = self.get_view_class(
            ListAdminView, model, list_per_page=10, list_editable=[])(req) 
Example 17
Project: ideascube   Author: ideascube   File: ideascube_tags.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def _remove_qs(params, **kwargs):
    existing = dict(params)
    for key, value in kwargs.items():
        try:
            existing[key].remove(value)
        except (KeyError, ValueError):
            pass
        else:
            if not existing[key]:
                del existing[key]
    params = QueryDict(mutable=True)
    params.update(MultiValueDict(existing))
    params.pop('page', None)  # Changing search context, reset page.
    return params 
Example 18
Project: ideascube   Author: ideascube   File: test_templatetags.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_is_in_qs_empty():
    assert _is_in_qs(QueryDict(), 'foo', 'bar') == False 
Example 19
Project: ideascube   Author: ideascube   File: test_templatetags.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_is_in_qs_is_in():
    query = QueryDict(mutable=True)
    query.update({'foo': 'bar'})
    assert _is_in_qs(query, 'foo', 'bar') == True 
Example 20
Project: ideascube   Author: ideascube   File: test_templatetags.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_is_in_qs_wrong_value():
    query = QueryDict(mutable=True)
    query.update({'foo': 'bar'})
    assert _is_in_qs(query, 'foo', 'baz') == False 
Example 21
Project: ideascube   Author: ideascube   File: test_templatetags.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_is_in_qs_wrong_key():
    query = QueryDict(mutable=True)
    query.update({'foo': 'bar'})
    assert _is_in_qs(query, 'key', 'bar') == False 
Example 22
Project: ideascube   Author: ideascube   File: test_templatetags.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_add_qs_to_identical():
    orig = QueryDict(mutable=True)
    orig.update({'bar': 'foo', 'foo': 'bar'})
    params = _add_qs(orig, foo='bar', bar='foo')
    assert dict(params) == {'bar': ['foo'], 'foo': ['bar']} 
Example 23
Project: ideascube   Author: ideascube   File: test_templatetags.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_add_qs_to_existing():
    orig = QueryDict(mutable=True)
    orig.update({'foo': 'val1'})
    params = _add_qs(orig, foo='val2')
    assert dict(params) == {'foo': ['val1', 'val2']} 
Example 24
Project: ideascube   Author: ideascube   File: test_templatetags.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_replace_qs_to_empty():
    params = _replace_qs(QueryDict(mutable=True), foo='bar')
    assert dict(params) == {'foo': ['bar']} 
Example 25
Project: ideascube   Author: ideascube   File: test_templatetags.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_replace_qs_to_identical():
    orig = QueryDict(mutable=True)
    orig.update({'foo': 'bar'})
    params = _replace_qs(orig, foo='bar')
    assert dict(params) == {'foo': ['bar']} 
Example 26
Project: ideascube   Author: ideascube   File: test_templatetags.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_replace_qs_to_existing():
    orig = QueryDict(mutable=True)
    orig.update({'foo': 'val1'})
    params = _replace_qs(orig, foo='val2')
    assert dict(params) == {'foo': ['val2']} 
Example 27
Project: ideascube   Author: ideascube   File: test_templatetags.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_remove_qs_to_not_existing():
    orig = QueryDict(mutable=True)
    orig.update({'bar': 'foo'})
    params = _remove_qs(orig, foo='bar')
    assert dict(params) == {'bar': ['foo']} 
Example 28
Project: ideascube   Author: ideascube   File: test_templatetags.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_remove_qs_to_value_not_existing():
    orig = QueryDict(mutable=True)
    orig.update({'bar': 'foo'})
    params = _remove_qs(orig, bar='bar')
    assert dict(params) == {'bar': ['foo']} 
Example 29
Project: ideascube   Author: ideascube   File: test_templatetags.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_remove_qs_to_one():
    orig = QueryDict(mutable=True)
    orig.update({'foo': 'val1'})

    params = _remove_qs(orig, foo='val1')
    assert dict(params) == {} 
Example 30
Project: ideascube   Author: ideascube   File: test_templatetags.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_remove_qs_to_several():
    orig = QueryDict(mutable=True)
    orig.update({'foo': 'val1'})
    orig.update({'foo': 'val2'})
    assert dict(orig) == {'foo': ['val1', 'val2']}
    params = _remove_qs(orig, foo='val2')
    assert dict(params) == {'foo': ['val1']}