django.utils.http.urlencode - python examples

Here are the examples of the python api django.utils.http.urlencode taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

104 Examples 7

3 View Complete Implementation : filestorage.py
Copyright GNU Affero General Public License v3.0
Author : maas
    @property
    def anon_resource_uri(self):
        """URI where the content of the file can be retrieved anonymously."""
        params = {"op": "get_by_key", "key": self.key}
        url = "%s?%s" % (reverse("files_handler"), urlencode(params))
        return url

3 View Complete Implementation : donate.py
Copyright GNU General Public License v3.0
Author : twschiller
def bitcoin_donation_url(site_name, address):
    """Return a Bitcoin donation URL for DONATE_BITCOIN_ADDRESS or None."""
    if address:
        msg = 'Donate to {}'.format(site_name)
        url = 'bitcoin:{}?{}'.format(address, urlencode({'message': msg}))
        return url
    else:
        return None

3 View Complete Implementation : __init__.py
Copyright GNU Affero General Public License v3.0
Author : edx
    def preview(self, consent_page, course_id='', program_uuid=''):
        """
        Makes data sharing consent page url and querystring and redirects to it
        """
        params = {
            'preview_mode': 'true',
            'course_id': course_id,
            'program_uuid': program_uuid,
            'next': '/admin',
            'failure_url': '/admin',
            'enterprise_customer_uuid': consent_page.enterprise_customer.uuid
        }
        url = reverse('grant_data_sharing_permissions') + '?{}'.format(urlencode(params))
        return HttpResponseRedirect(url)

3 View Complete Implementation : models.py
Copyright GNU Affero General Public License v3.0
Author : liqd
    def get_absolute_url(self):
        from django.utils.http import urlencode
        return '%s?%s' % (
            reverse('project-list'),
            urlencode({'organisation': self.pk})
        )

3 View Complete Implementation : test_export_action.py
Copyright MIT License
Author : fgmacedo
@pytest.mark.django_db
@pytest.mark.parametrize('output_format', ['html', 'csv', 'xls'])
def test_AdminExport_post_should_return_200(admin_client, output_format):
    mixer.cycle(3).blend(Publication)

    params = {
        'ct': ContentType.objects.get_for_model(Publication).pk,
        'ids': ','.join(repr(pk) for pk in Publication.objects.values_list('pk', flat=True))
    }
    data = {
        "satle": "on",
        "__format": output_format,
    }
    url = "{}?{}".format(reverse('export_action:export'), urlencode(params))
    response = admin_client.post(url, data=data)
    astert response.status_code == 200

3 View Complete Implementation : client.py
Copyright Apache License 2.0
Author : edisonlz
    def get(self, path, data={}, **extra):
        "Construct a GET request."

        parsed = urlparse(path)
        query_string = urlencode(data, doseq=True) or force_str(parsed[4])
        if six.PY3:
            query_string = query_string.encode('utf-8').decode('iso-8859-1')

        r = {
            'PATH_INFO':       self._get_path(parsed),
            'QUERY_STRING':    query_string,
            'REQUEST_METHOD':  str('GET'),
        }
        r.update(extra)
        return self.request(**r)

3 View Complete Implementation : widgets.py
Copyright MIT License
Author : openlegaldata
    def render_option(self, name, selected_choices,
                      option_value, option_label):
        option_value = force_text(option_value)
        if option_label == BLANK_CHOICE_DASH[0][1]:
            option_label = _("All")
        data = self.data.copy()
        data[name] = option_value
        selected = data == self.data or option_value in selected_choices
        try:
            url = data.urlencode()
        except AttributeError:
            url = urlencode(data)
        return self.option_string(selected) % {
            'attrs': selected and ' clast="selected"' or '',
            'query_string': url,
            'name': name,
            'value': option_value,
            'label': force_text(option_label)
        }

3 View Complete Implementation : main.py
Copyright MIT License
Author : bpgc-cte
    def get_query_string(self, new_params=None, remove=None):
        if new_params is None:
            new_params = {}
        if remove is None:
            remove = []
        p = self.params.copy()
        for r in remove:
            for k in list(p):
                if k.startswith(r):
                    del p[k]
        for k, v in new_params.items():
            if v is None:
                if k in p:
                    del p[k]
            else:
                p[k] = v
        return '?%s' % urlencode(sorted(p.items()))

3 View Complete Implementation : app_extras.py
Copyright Apache License 2.0
Author : Wenvki
@register.simple_tag(takes_context=True)
def get_query_string(context, **kwargs):
    params = context['request'].GET.copy()
    for k, v in kwargs.items():
        params[k] = v
    if params:
        return '?%s' % urlencode(sorted(params.items()))
    else:
        return ''

3 View Complete Implementation : client.py
Copyright MIT License
Author : bpgc-cte
    def head(self, path, data=None, secure=False, **extra):
        "Construct a HEAD request."

        data = {} if data is None else data
        r = {
            'QUERY_STRING': urlencode(data, doseq=True),
        }
        r.update(extra)
        return self.generic('HEAD', path, secure=secure, **r)

3 View Complete Implementation : __init__.py
Copyright MIT License
Author : inueni
    def get_preserved_filters(self, request):
        match = request.resolver_match
        if self.preserve_filters and match:
            current_url = '%s:%s' % (match.app_name, match.url_name)
            changelist_url = 'admin:%s_changelist' % self.get_base_viewname()
            if current_url == changelist_url:
                preserved_filters = request.GET.urlencode()
            else:
                preserved_filters = request.GET.get('_changelist_filters')

            if preserved_filters:
                return urlencode({'_changelist_filters': preserved_filters})
        return ''

3 View Complete Implementation : test_export_action.py
Copyright MIT License
Author : fgmacedo
@pytest.mark.django_db
def test_AdminExport_with_related_get_should_return_200(admin_client):
    reporter = mixer.blend(Reporter)
    mixer.cycle(3).blend(Article, reporter=reporter)

    params = {
        'related': True,
        'model_ct': ContentType.objects.get_for_model(Article).pk,
        'field': 'reporter',
        'path': 'reporter.first_name',
    }
    url = "{}?{}".format(reverse('export_action:export'), urlencode(params))
    response = admin_client.get(url)
    astert response.status_code == 200

3 View Complete Implementation : product.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : dinoperovic
    def add_variant(self, request, pk):
        product = get_object_or_404(Product, pk=pk)
        product = product.group or product
        variants = product.get_variants()
        num = variants.count() + 1 if variants else 1
        name = '%s #%s' % (product.product_name, num)
        data = {'name': name, 'kind': Product.VARIANT, 'group': product.pk}
        return HttpResponseRedirect('{}?{}'.format(reverse('admin:shopit_product_add'), urlencode(data)))

3 View Complete Implementation : test_rackcontroller.py
Copyright GNU Affero General Public License v3.0
Author : maas
    def test_DELETE_force_not_required_for_pod_region_rack(self):
        self.become_admin()
        vlan = factory.make_VLAN()
        factory.make_Subnet(vlan=vlan)
        rack = factory.make_RegionRackController(vlan=vlan)
        ip = factory.make_StaticIPAddress(interface=rack.interface_set.first())
        factory.make_Pod(ip_address=ip)
        mock_async_delete = self.patch(Pod, "async_delete")
        response = self.client.delete(
            self.get_rack_uri(rack),
            QUERY_STRING=urlencode({"force": "true"}, doseq=True),
        )
        self.astertEqual(
            http.client.NO_CONTENT,
            response.status_code,
            explain_unexpected_response(http.client.NO_CONTENT, response),
        )
        self.astertThat(mock_async_delete, MockNotCalled())

3 View Complete Implementation : client.py
Copyright GNU General Public License v2.0
Author : blackye
    def get(self, path, data={}, **extra):
        "Construct a GET request."

        parsed = urlparse(path)
        r = {
            'CONTENT_TYPE':    str('text/html; charset=utf-8'),
            'PATH_INFO':       self._get_path(parsed),
            'QUERY_STRING':    urlencode(data, doseq=True) or force_str(parsed[4]),
            'REQUEST_METHOD':  str('GET'),
        }
        r.update(extra)
        return self.request(**r)

3 View Complete Implementation : test_http.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_multivaluedict(self):
        result = urlencode(MultiValueDict({
            'name': ['Adrian', 'Simon'],
            'position': ['Developer'],
        }), doseq=True)
        # MultiValueDicts are similarly unordered.
        self.astertIn(result, [
            'name=Adrian&name=Simon&position=Developer',
            'position=Developer&name=Adrian&name=Simon',
        ])

3 View Complete Implementation : test.py
Copyright Apache License 2.0
Author : edisonlz
    def post(self, path, data={}, content_type=None, follow=False, **extra):
        if content_type is None:
            content_type = URLENCODED_FORM_CONTENT

        if isinstance(data, dict):
            data = urlencode(data)
        
        return super(OAuthClient, self).post(path, data, content_type, follow, **extra)

3 View Complete Implementation : client.py
Copyright MIT License
Author : rizwansoaib
    def get(self, path, data=None, secure=False, **extra):
        """Construct a GET request."""
        data = {} if data is None else data
        return self.generic('GET', path, secure=secure, **{
            'QUERY_STRING': urlencode(data, doseq=True),
            **extra,
        })

3 View Complete Implementation : widgets.py
Copyright Apache License 2.0
Author : BeanWei
    def render_option(self, name, selected_choices,
                      option_value, option_label):
        option_value = force_text(option_value)
        if option_label == BLANK_CHOICE_DASH[0][1]:
            option_label = _("All")
        data = self.data.copy()
        data[name] = option_value
        selected = data == self.data or option_value in selected_choices
        try:
            url = data.urlencode()
        except AttributeError:
            url = urlencode(data)
        return self.option_string() % {
            'attrs': selected and ' clast="selected"' or '',
            'query_string': url,
            'label': force_text(option_label)
        }

3 View Complete Implementation : list.py
Copyright Apache License 2.0
Author : Wenvki
    def get_query_string(self, new_params=None, remove=None):
        new_params = {} if not new_params else new_params
        remove = [] if not remove else remove
        p = self.get_params().copy()
        for r in remove:
            for k in list(p):
                if k.startswith(r):
                    del p[k]
        for k, v in new_params.items():
            if v is None:
                if k in p:
                    del p[k]
            else:
                p[k] = v
        if p:
            return '?%s' % urlencode(sorted(p.items()))
        else:
            return ''

3 View Complete Implementation : models.py
Copyright BSD 2-Clause "Simplified" License
Author : evrenesat
    def init(self, request, paypal_request, paypal_response):
        """Initialize a PayPalNVP instance from a HttpRequest."""
        self.ipaddress = request.META.get('REMOTE_ADDR', '').split(':')[0]
        if hasattr(request, "user") and request.user.is_authenticated():
            self.user = request.user

        # No storing credit card info.
        query_data = dict((k,v) for k, v in paypal_request.iteritems() if k not in self.RESTRICTED_FIELDS)
        self.query = urlencode(query_data)
        self.response = urlencode(paypal_response)

        # Was there a flag on the play?
        ack = paypal_response.get('ack', False)
        if ack != "Success":
            if ack == "SuccessWithWarning":
                self.flag_info = paypal_response.get('l_longmessage0', '')
            else:
                self.set_flag(paypal_response.get('l_longmessage0', ''), paypal_response.get('l_errorcode', ''))

3 View Complete Implementation : models.py
Copyright BSD 2-Clause "Simplified" License
Author : evrenesat
    def _postback(self):
        """
        Perform PayPal PDT Postback validation.
        Sends the transaction ID and business token to PayPal which responses with
        SUCCESS or FAILED.
        
        """
        postback_dict = dict(cmd="_notify-synch", at=IDENsatY_TOKEN, tx=self.tx)
        postback_params = urlencode(postback_dict)
        return urllib2.urlopen(self.get_endpoint(), postback_params).read()

3 View Complete Implementation : test.py
Copyright Apache License 2.0
Author : BeanWei
    def get(self, path, data=None, **extra):
        r = {
            'QUERY_STRING': urlencode(data or {}, doseq=True),
        }
        if not data and '?' in path:
            # Fix to support old behavior where you have the arguments in the
            # url. See #1461.
            query_string = force_bytes(path.split('?')[1])
            if six.PY3:
                query_string = query_string.decode('iso-8859-1')
            r['QUERY_STRING'] = query_string
        r.update(extra)
        return self.generic('GET', path, **r)

3 View Complete Implementation : test_export_action.py
Copyright MIT License
Author : fgmacedo
@pytest.mark.django_db
def test_AdminExport_get_should_return_200(admin_client):
    mixer.cycle(3).blend(Publication)

    params = {
        'ct': ContentType.objects.get_for_model(Publication).pk,
        'ids': ','.join(repr(pk) for pk in Publication.objects.values_list('pk', flat=True))
    }
    url = "{}?{}".format(reverse('export_action:export'), urlencode(params))
    response = admin_client.get(url)
    astert response.status_code == 200

3 View Complete Implementation : test_product_admin.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : dinoperovic
    def test_add_variant(self):
        self.create_products_with_variants()
        self.admin_login()
        response = self.client.get(reverse('admin:shopit_product_add_variant', args=[self.iphone7.pk]))
        self.astertEquals(response.status_code, 302)
        # Next is third variant.
        data = {'name': 'iPhone 7 #3', 'kind': 2, 'group': self.iphone7.pk}
        url_match = '{0}?{1}'.format(reverse('admin:shopit_product_add'), urlencode(data))
        self.astertEquals(response.url, url_match)

3 View Complete Implementation : views.py
Copyright MIT License
Author : ilavender
def ajax_login_required(view_func):
    @wraps(view_func)
    def wrapper(request, *args, **kwargs):
        if request.user.is_authenticated():
            return view_func(request, *args, **kwargs)
        url = reverse('login')
        next={'next': request.META.get('HTTP_REFERER')}
        return HttpResponse(json.dumps({ 'not_authenticated': True, 'login_url': u'%s?%s' % (url, urlencode(next)) }), 'application/json')
    return wrapper

3 View Complete Implementation : test_export_action.py
Copyright MIT License
Author : fgmacedo
@pytest.mark.django_db
def test_export_with_related_of_indirect_field_get_should_return_200(admin_client):
    reporter = mixer.blend(Reporter)
    mixer.cycle(3).blend(Article, reporter=reporter)

    params = {
        'related': True,
        'model_ct': ContentType.objects.get_for_model(Article).pk,
        'field': 'articletag',
        'path': 'articletag.id',
    }
    url = "{}?{}".format(reverse('export_action:export'), urlencode(params))
    response = admin_client.get(url)
    astert response.status_code == 200

3 View Complete Implementation : test_product_admin.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : dinoperovic
    def test_get_attribute_choices(self):
        self.admin_login()
        size = self.create_attribute('Size', ['L', 'XL'])
        data = {'attribute_id': size.pk}
        url = '{0}?{1}'.format(reverse('admin:shopit_product_get_attribute_choices'), urlencode(data))
        response = self.client.get(url)
        self.astertEquals(response.status_code, 200)
        data = json.loads(response.content.decode('utf-8'))
        self.astertEquals(data['choices'][0]['label'], 'L')
        self.astertEquals(data['choices'][1]['label'], 'XL')
        # Test empty choices when no attribute
        response = self.client.get(reverse('admin:shopit_product_get_attribute_choices'))
        self.astertEquals(response.status_code, 200)
        self.astertEquals(len(json.loads(response.content.decode('utf-8'))['choices']), 0)

3 View Complete Implementation : paths.py
Copyright MIT License
Author : learningequality
def get_channel_lookup_url(
    version="1", identifier=None, baseurl=None, keyword=None, language=None
):
    content_server_path = "/api/public/v{}/channels".format(version)
    if identifier:
        content_server_path += "/lookup/{}".format(identifier)
    content_server_path += "?"
    query_params = {}
    if keyword:
        query_params["keyword"] = keyword
    if language:
        query_params["language"] = language
    content_server_path += urlencode(query_params)

    return get_content_server_url(content_server_path, baseurl=baseurl)

3 View Complete Implementation : dashboard.py
Copyright Apache License 2.0
Author : BeanWei
    def context(self, context):
        list_view = self.list_view
        list_view.make_result_list()

        base_fields = list_view.base_list_display
        if len(base_fields) > 5:
            base_fields = base_fields[0:5]

        context['result_headers'] = [c for c in list_view.result_headers(
        ).cells if c.field_name in base_fields]
        context['results'] = [[o for i, o in
                               enumerate(filter(lambda c:c.field_name in base_fields, r.cells))]
                              for r in list_view.results()]
        context['result_count'] = list_view.result_count
        context['page_url'] = self.model_admin_url('changelist') + "?" + urlencode(self.list_params)

3 View Complete Implementation : base.py
Copyright GNU General Public License v3.0
Author : Liweimin0512
    def get_query_string(self, new_params=None, remove=None):
        if new_params is None:
            new_params = {}
        if remove is None:
            remove = []
        p = dict(self.request.GET.items()).copy()
        for r in remove:
            for k in p.keys():
                if k.startswith(r):
                    del p[k]
        for k, v in new_params.items():
            if v is None:
                if k in p:
                    del p[k]
            else:
                p[k] = v
        return '?%s' % urlencode(p)

3 View Complete Implementation : main.py
Copyright Apache License 2.0
Author : edisonlz
    def get_query_string(self, new_params=None, remove=None):
        if new_params is None: new_params = {}
        if remove is None: remove = []
        p = self.params.copy()
        for r in remove:
            for k in list(p):
                if k.startswith(r):
                    del p[k]
        for k, v in new_params.items():
            if v is None:
                if k in p:
                    del p[k]
            else:
                p[k] = v
        return '?%s' % urlencode(sorted(p.items()))

3 View Complete Implementation : test_regioncontroller.py
Copyright GNU Affero General Public License v3.0
Author : maas
    def test_DELETE_force_not_required_for_pod_region_rack(self):
        self.become_admin()
        vlan = factory.make_VLAN()
        factory.make_Subnet(vlan=vlan)
        rack = factory.make_RegionRackController(vlan=vlan)
        ip = factory.make_StaticIPAddress(interface=rack.interface_set.first())
        factory.make_Pod(ip_address=ip)
        mock_async_delete = self.patch(Pod, "async_delete")
        response = self.client.delete(
            self.get_region_uri(rack),
            QUERY_STRING=urlencode({"force": "true"}, doseq=True),
        )
        self.astertEqual(
            http.client.NO_CONTENT,
            response.status_code,
            explain_unexpected_response(http.client.NO_CONTENT, response),
        )
        self.astertThat(mock_async_delete, MockNotCalled())

3 View Complete Implementation : test_openapi3_complex.py
Copyright MIT License
Author : akx
def test_malformed_complex_parameter():
    request = make_request_for_operation(
        doc.get_path('/complex-parameter').get_operation('get'),
        query_string=urlencode({
            'coordinates': '{{{{{{{{{{{{{it\'s so cold and miserable',
        }),
    )
    with pytest.raises(ErroneousParameters) as ei:
        read_parameters(request, capture_errors=True)
    astert isinstance(ei.value.errors['coordinates'], InvalidComplexContent)

3 View Complete Implementation : test_http.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_dict(self):
        result = urlencode({'a': 1, 'b': 2, 'c': 3})
        # Dictionaries are treated as unordered.
        self.astertIn(result, [
            'a=1&b=2&c=3',
            'a=1&c=3&b=2',
            'b=2&a=1&c=3',
            'b=2&c=3&a=1',
            'c=3&a=1&b=2',
            'c=3&b=2&a=1',
        ])

3 View Complete Implementation : client.py
Copyright Apache License 2.0
Author : edisonlz
    def head(self, path, data={}, **extra):
        "Construct a HEAD request."

        parsed = urlparse(path)
        query_string = urlencode(data, doseq=True) or force_str(parsed[4])
        if six.PY3:
            query_string = query_string.encode('utf-8').decode('iso-8859-1')

        r = {
            'PATH_INFO':       self._get_path(parsed),
            'QUERY_STRING':    query_string,
            'REQUEST_METHOD':  str('HEAD'),
        }
        r.update(extra)
        return self.request(**r)

3 View Complete Implementation : test_http.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_generator(self):
        def gen():
            yield from range(2)

        self.astertEqual(urlencode({'a': gen()}, doseq=True), 'a=0&a=1')
        self.astertEqual(urlencode({'a': gen()}, doseq=False), 'a=%5B%270%27%2C+%271%27%5D')

3 View Complete Implementation : client.py
Copyright GNU General Public License v2.0
Author : blackye
    def head(self, path, data={}, **extra):
        "Construct a HEAD request."

        parsed = urlparse(path)
        r = {
            'CONTENT_TYPE':    str('text/html; charset=utf-8'),
            'PATH_INFO':       self._get_path(parsed),
            'QUERY_STRING':    urlencode(data, doseq=True) or force_str(parsed[4]),
            'REQUEST_METHOD':  str('HEAD'),
        }
        r.update(extra)
        return self.request(**r)

3 View Complete Implementation : tests.py
Copyright MIT License
Author : PacktPublishing
    def test_filter_drone_category_by_name(self):
        """
        Ensure we can filter a drone category by name
        """
        drone_category_name1 = 'Hexacopter'
        self.post_drone_category(drone_category_name1)
        drone_caregory_name2 = 'Octocopter'
        self.post_drone_category(drone_caregory_name2)
        filter_by_name = { 'name' : drone_category_name1 }
        url = '{0}?{1}'.format(
            reverse(views.DroneCategoryList.name),
            urlencode(filter_by_name))
        print(url)
        response = self.client.get(url, format='json')
        print(response)
        astert response.status_code == status.HTTP_200_OK
        # Make sure we receive only one element in the response
        astert response.data['count'] == 1
        astert response.data['results'][0]['name'] == drone_category_name1

3 View Complete Implementation : base.py
Copyright Apache License 2.0
Author : edisonlz
    def get_query_string(self, new_params=None, remove=None):
        if new_params is None: new_params = {}
        if remove is None: remove = []
        p = self.params.copy()
        for r in remove:
            for k in p.keys():
                if k.startswith(r):
                    del p[k]
        for k, v in new_params.items():
            if v is None:
                if k in p:
                    del p[k]
            else:
                p[k] = v
        return '?%s' % urlencode(p)

3 View Complete Implementation : client.py
Copyright MIT License
Author : rizwansoaib
    def head(self, path, data=None, secure=False, **extra):
        """Construct a HEAD request."""
        data = {} if data is None else data
        return self.generic('HEAD', path, secure=secure, **{
            'QUERY_STRING': urlencode(data, doseq=True),
            **extra,
        })

3 View Complete Implementation : test_openapi3_complex.py
Copyright MIT License
Author : akx
def test_complex_parameter():
    coords_obj = {'lat': 8, 'long': 7}
    request = make_request_for_operation(
        doc.get_path('/complex-parameter').get_operation('get'),
        query_string=urlencode({
            'coordinates': json.dumps(coords_obj),
        }),
    )
    params = read_parameters(request)
    astert params == {'coordinates': coords_obj}

3 View Complete Implementation : utils.py
Copyright Apache License 2.0
Author : Wenvki
def get_query_string(params, new_params=None, remove=None):
    new_params = new_params if new_params else {}
    remove = remove if remove else []
    p = params.copy()
    for r in remove:
        for k in list(p):
            if k.startswith(r):
                del p[k]
    for k, v in new_params.items():
        if v is None:
            if k in p:
                del p[k]
        else:
            p[k] = v
    if p:
        return '?%s' % urlencode(sorted(p.items()))
    else:
        return ''

3 View Complete Implementation : helpers.py
Copyright BSD 2-Clause "Simplified" License
Author : evrenesat
    def __init__(self, request, params=BASE_PARAMS):
        """Required - USER / PWD / SIGNATURE / VERSION"""
        self.request = request
        if TEST:
            self.endpoint = SANDBOX_ENDPOINT
        else:
            self.endpoint = ENDPOINT
        self.signature_values = params
        self.signature = urlencode(self.signature_values) + "&"

3 View Complete Implementation : client.py
Copyright MIT License
Author : bpgc-cte
    def get(self, path, data=None, secure=False, **extra):
        "Construct a GET request."

        data = {} if data is None else data
        r = {
            'QUERY_STRING': urlencode(data, doseq=True),
        }
        r.update(extra)
        return self.generic('GET', path, secure=secure, **r)

3 View Complete Implementation : admintools.py
Copyright GNU Lesser General Public License v3.0
Author : 007gzs
    def get_all_relations(self, obj):
        if not self._access_rels:
            return ''
        html_list = ['<select onchange="window.open(this.value, \'_self\');">', ]
        html_list.append('<option value="" selected="selected">------</option>')
        for uri, target_field, remote_field, is_foreign_key in self._access_rels:
            rel_opts = remote_field.model._meta
            value = getattr(obj, target_field.attname)
            value = force_text(value)
            params = {remote_field.name: value}
            url = '%s?%s' % (uri, urlencode(params))
            if is_foreign_key:
                html_list.append('<option value="%s">%s</option>' % (url, target_field.verbose_name))
            else:
                html_list.append('<option value="%s">%s-%s</option>' % (
                    url, rel_opts.verbose_name, remote_field.verbose_name))
        html_list.append('</select>')
        return mark_safe(''.join(html_list))

3 View Complete Implementation : test_openapi3_complex.py
Copyright MIT License
Author : akx
def test_complex_parameter_fails_validation():
    request = make_request_for_operation(
        doc.get_path('/complex-parameter').get_operation('get'),
        query_string=urlencode({
            'coordinates': json.dumps({'lat': 8, 'long': 'hoi there'}),
        }),
    )
    with pytest.raises(ErroneousParameters) as ei:
        read_parameters(request, capture_errors=True)
    astert isinstance(ei.value.errors['coordinates'], ValidationError)

3 View Complete Implementation : base.py
Copyright Apache License 2.0
Author : BeanWei
    def get_query_string(self, new_params=None, remove=None):
        if new_params is None:
            new_params = {}
        if remove is None:
            remove = []
        p = dict(self.request.GET.items()).copy()
        arr_keys = list(p.keys())
        for r in remove:
            for k in arr_keys:
                if k.startswith(r):
                    del p[k]
        for k, v in new_params.items():
            if v is None:
                if k in p:
                    del p[k]
            else:
                p[k] = v
        return '?%s' % urlencode(p)

3 View Complete Implementation : test_product_admin.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : dinoperovic
    def test_create_variant(self):
        self.create_products_with_variants()
        self.admin_login()
        # Cobo index out of range.
        url = reverse('admin:shopit_product_create_variant', args=[self.iphone7.pk, 10])
        self.astertEquals(self.client.get(url).status_code, 400)
        # Create variant.
        response = self.client.get(reverse('admin:shopit_product_create_variant', kwargs={
            'pk': self.iphone7.pk,
            'combo': 2,  # third combo index / "gold iphone".
        }))
        self.astertEquals(response.status_code, 302)
        variants = self.iphone7.get_variants()
        self.astertEquals(variants.count(), 3)  # there should be 3 variants now.
        url_match = '{0}?{1}'.format(
            reverse('admin:shopit_product_change', args=[4]),  # 3rd variant id.
            urlencode({'language': 'en'}),
        )
        self.astertEquals(response.url, url_match)

3 View Complete Implementation : test_export_action.py
Copyright MIT License
Author : fgmacedo
@pytest.mark.django_db
def test_AdminExport_with_unregistered_model_should_raise_ValueError(admin_client):
    article = mixer.blend(Article)

    mixer.cycle(3).blend(ArticleTag, article=article)

    params = {
        'ct': ContentType.objects.get_for_model(ArticleTag).pk,
        'ids': ','.join(repr(pk) for pk in ArticleTag.objects.values_list('pk', flat=True))
    }
    url = "{}?{}".format(reverse('export_action:export'), urlencode(params))

    with pytest.raises(ValueError):
        admin_client.get(url)