Python django.utils.http.urlencode() Examples

The following are 30 code examples for showing how to use django.utils.http.urlencode(). 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.utils.http , or try the search function .

Example 1
Project: StormOnline   Author: stormsha   File: base.py    License: Apache License 2.0 6 votes vote down vote up
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) 
Example 2
Project: django-idcops   Author: Wenvki   File: list.py    License: Apache License 2.0 6 votes vote down vote up
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 '' 
Example 3
Project: django-idcops   Author: Wenvki   File: utils.py    License: Apache License 2.0 6 votes vote down vote up
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 '' 
Example 4
Project: GTDWeb   Author: lanbing510   File: main.py    License: GNU General Public License v2.0 6 votes vote down vote up
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())) 
Example 5
Project: GTDWeb   Author: lanbing510   File: options.py    License: GNU General Public License v2.0 6 votes vote down vote up
def get_preserved_filters(self, request):
        """
        Returns the preserved filters querystring.
        """
        match = request.resolver_match
        if self.preserve_filters and match:
            opts = self.model._meta
            current_url = '%s:%s' % (match.app_name, match.url_name)
            changelist_url = 'admin:%s_%s_changelist' % (opts.app_label, opts.model_name)
            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 '' 
Example 6
Project: sugardough   Author: mozilla   File: helpers.py    License: Apache License 2.0 6 votes vote down vote up
def urlparams(url_, hash=None, **query):
    """Add a fragment and/or query paramaters to a URL.

    New query params will be appended to exising parameters, except duplicate
    names, which will be replaced.
    """
    url = urlparse.urlparse(url_)
    fragment = hash if hash is not None else url.fragment

    # Use dict(parse_qsl) so we don't get lists of values.
    query_dict = dict(urlparse.parse_qsl(url.query))
    query_dict.update(query)

    query_string = urlencode(
        [(k, v) for k, v in query_dict.items() if v is not None])
    new = urlparse.ParseResult(url.scheme, url.netloc, url.path, url.params,
                               query_string, fragment)
    return new.geturl() 
Example 7
Project: bioforum   Author: reBiocoder   File: main.py    License: MIT License 6 votes vote down vote up
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())) 
Example 8
Project: bioforum   Author: reBiocoder   File: options.py    License: MIT License 6 votes vote down vote up
def get_preserved_filters(self, request):
        """
        Return the preserved filters querystring.
        """
        match = request.resolver_match
        if self.preserve_filters and match:
            opts = self.model._meta
            current_url = '%s:%s' % (match.app_name, match.url_name)
            changelist_url = 'admin:%s_%s_changelist' % (opts.app_label, opts.model_name)
            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 '' 
Example 9
Project: weibo-analysis-system   Author: Superbsco   File: base.py    License: MIT License 6 votes vote down vote up
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) 
Example 10
Project: myblog   Author: myminwang   File: base.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
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) 
Example 11
Project: CTF_AWD_Platform   Author: xuchaoa   File: base.py    License: MIT License 6 votes vote down vote up
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) 
Example 12
Project: janeway   Author: BirkbeckCTP   File: logic.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def register_crossref_doi(identifier):
    from utils import setting_handler

    domain = identifier.article.journal.domain
    pingback_url = urlencode({'pingback': 'http://{0}{1}'.format(domain, reverse('crossref_pingback'))})

    use_crossref = setting_handler.get_setting('Identifiers', 'use_crossref',
                                               identifier.article.journal).processed_value

    if not use_crossref:
        logger.info("[DOI] Not using Crossref DOIs on this journal. Aborting registration.")
        return 'Crossref Disabled', 'Disabled'

    test_mode = setting_handler.get_setting(
            'Identifiers', 'crossref_test', identifier.article.journal
    ).processed_value or settings.DEBUG

    if test_mode:
        util_models.LogEntry.add_entry('Submission', "DOI registration running in test mode", 'Info',
                                       target=identifier.article)
    else:
        util_models.LogEntry.add_entry('Submission', "DOI registration running in live mode", 'Info',
                                       target=identifier.article)

    return send_crossref_deposit(test_mode, identifier) 
Example 13
Project: django_OA   Author: abaoMAO   File: base.py    License: GNU General Public License v3.0 6 votes vote down vote up
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) 
Example 14
Project: website   Author: outreachy   File: mixins.py    License: GNU General Public License v3.0 6 votes vote down vote up
def dispatch(self, request, *args, **kwargs):
        try:
            # Check that the logged-in user has a Comrade instance too:
            # even just trying to access the field will fail if not.
            request.user.comrade
        except Comrade.DoesNotExist:
            # If not, redirect to create one and remember to come back
            # here afterward.
            return HttpResponseRedirect(
                '{account_url}?{query_string}'.format(
                    account_url=reverse('account'),
                    query_string=urlencode({'next': request.path})))
        return super(ComradeRequiredMixin, self).dispatch(request, *args, **kwargs)

# If the logged-in user doesn't have an ApplicantApproval object,
# redirect them to create one.
# If the logged-in user has an ApplicantApproval object that isn't approved,
# redirect them to the eligibility results page.
#
# This mixin requires a 'round_slug' view keyword argument.
#
# Note that LoginRequiredMixin must be to the left of this class in the
# view's list of parent classes, and the base View must be to the right. 
Example 15
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: main.py    License: MIT License 6 votes vote down vote up
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())) 
Example 16
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: options.py    License: MIT License 6 votes vote down vote up
def get_preserved_filters(self, request):
        """
        Return the preserved filters querystring.
        """
        match = request.resolver_match
        if self.preserve_filters and match:
            opts = self.model._meta
            current_url = '%s:%s' % (match.app_name, match.url_name)
            changelist_url = 'admin:%s_%s_changelist' % (opts.app_label, opts.model_name)
            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 '' 
Example 17
Project: wagtail   Author: wagtail   File: wagtailadmin_tags.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def querystring(context, **kwargs):
    """
    Print out the current querystring. Any keyword arguments to this template
    tag will be added to the querystring before it is printed out.

        <a href="/page/{% querystring key='value' %}">

    Will result in something like:

        <a href="/page/?foo=bar&key=value">
    """
    request = context['request']
    querydict = request.GET.copy()
    # Can't do querydict.update(kwargs), because QueryDict.update() appends to
    # the list of values, instead of replacing the values.
    for key, value in kwargs.items():
        if value is None:
            # Remove the key if the value is None
            querydict.pop(key, None)
        else:
            # Set the key otherwise
            querydict[key] = str(value)

    return '?' + querydict.urlencode() 
Example 18
Project: wagtail   Author: wagtail   File: views.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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())) 
Example 19
Project: python   Author: Yeah-Kun   File: main.py    License: Apache License 2.0 6 votes vote down vote up
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())) 
Example 20
Project: python   Author: Yeah-Kun   File: options.py    License: Apache License 2.0 6 votes vote down vote up
def get_preserved_filters(self, request):
        """
        Returns the preserved filters querystring.
        """
        match = request.resolver_match
        if self.preserve_filters and match:
            opts = self.model._meta
            current_url = '%s:%s' % (match.app_name, match.url_name)
            changelist_url = 'admin:%s_%s_changelist' % (opts.app_label, opts.model_name)
            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 '' 
Example 21
Project: feedthefox   Author: mozilla   File: helpers.py    License: Mozilla Public License 2.0 6 votes vote down vote up
def urlparams(url_, hash=None, **query):
    """Add a fragment and/or query paramaters to a URL.

    New query params will be appended to exising parameters, except duplicate
    names, which will be replaced.
    """
    url = urlparse.urlparse(url_)
    fragment = hash if hash is not None else url.fragment

    # Use dict(parse_qsl) so we don't get lists of values.
    query_dict = dict(urlparse.parse_qsl(url.query))
    query_dict.update(query)

    query_string = urlencode(
        [(k, v) for k, v in query_dict.items() if v is not None])
    new = urlparse.ParseResult(url.scheme, url.netloc, url.path, url.params,
                               query_string, fragment)
    return new.geturl() 
Example 22
Project: django-subadmin   Author: inueni   File: __init__.py    License: MIT License 5 votes vote down vote up
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 '' 
Example 23
Project: django-subadmin   Author: inueni   File: __init__.py    License: MIT License 5 votes vote down vote up
def add_preserved_filters(self, context, url, popup=False, to_field=None):
        opts = context.get('opts')
        preserved_filters = context.get('preserved_filters')

        parsed_url = list(urlparse(url))
        parsed_qs = dict(parse_qsl(parsed_url[4]))
        merged_qs = dict()

        if opts and preserved_filters:
            preserved_filters = dict(parse_qsl(preserved_filters))

            match_url = '/%s' % url.partition(get_script_prefix())[2]
            try:
                match = resolve(match_url)
            except Resolver404:
                pass
            else:
                current_url = '%s:%s' % (match.app_name, match.url_name)
                changelist_url = 'admin:%s_changelist' % self.get_base_viewname()
                if changelist_url == current_url and '_changelist_filters' in preserved_filters:
                    preserved_filters = dict(parse_qsl(preserved_filters['_changelist_filters']))

            merged_qs.update(preserved_filters)

        if popup:
            from django.contrib.admin.options import IS_POPUP_VAR
            merged_qs[IS_POPUP_VAR] = 1
        if to_field:
            from django.contrib.admin.options import TO_FIELD_VAR
            merged_qs[TO_FIELD_VAR] = to_field

        merged_qs.update(parsed_qs)

        parsed_url[4] = urlencode(merged_qs)
        return urlunparse(parsed_url) 
Example 24
Project: open-synthesis   Author: twschiller   File: donate.py    License: GNU General Public License v3.0 5 votes vote down vote up
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 
Example 25
Project: coursys   Author: sfu-fas   File: auth.py    License: GNU General Public License v3.0 5 votes vote down vote up
def ForbiddenResponse(request, errormsg=None, exception=None):
    error = mark_safe("You do not have permission to access this resource.")
    if not request.user.is_authenticated:
        login_url = settings.LOGIN_URL + '?' + urllib.parse.urlencode({'next': request.get_full_path()})
        error += mark_safe(' You are <strong>not logged in</strong>, so maybe <a href="%s">logging in</a> would help.' % (login_url))
    return HttpError(request, status=403, title="Forbidden", error=error, errormsg=errormsg) 
Example 26
Project: coursys   Author: sfu-fas   File: auth.py    License: GNU General Public License v3.0 5 votes vote down vote up
def login_redirect(next_url):
    """
    Send the user to log in, and then to next_url
    """
    return HttpResponseRedirect(settings.LOGIN_URL + '?' + urlencode({'next': next_url})) 
Example 27
Project: django-oidc-rp   Author: impak-finance   File: views.py    License: MIT License 5 votes vote down vote up
def get(self, request):
        """ Processes GET requests. """
        # Defines common parameters used to bootstrap the authentication request.
        authentication_request_params = request.GET.dict()
        authentication_request_params.update({
            'scope': oidc_rp_settings.SCOPES,
            'response_type': 'code',
            'client_id': oidc_rp_settings.CLIENT_ID,
            'redirect_uri': request.build_absolute_uri(reverse('oidc_auth_callback')),
        })

        # States should be used! They are recommended in order to maintain state between the
        # authentication request and the callback.
        if oidc_rp_settings.USE_STATE:
            state = get_random_string(oidc_rp_settings.STATE_LENGTH)
            authentication_request_params.update({'state': state})
            request.session['oidc_auth_state'] = state

        # Nonces should be used too! In that case the generated nonce is stored both in the
        # authentication request parameters and in the user's session.
        if oidc_rp_settings.USE_NONCE:
            nonce = get_random_string(oidc_rp_settings.NONCE_LENGTH)
            authentication_request_params.update({'nonce': nonce, })
            request.session['oidc_auth_nonce'] = nonce

        # Stores the "next" URL in the session if applicable.
        next_url = request.GET.get('next')
        request.session['oidc_auth_next_url'] = next_url \
            if is_safe_url(url=next_url, allowed_hosts=(request.get_host(), )) else None

        # Redirects the user to authorization endpoint.
        query = urlencode(authentication_request_params)
        redirect_url = '{url}?{query}'.format(
            url=oidc_rp_settings.PROVIDER_AUTHORIZATION_ENDPOINT, query=query)
        return HttpResponseRedirect(redirect_url) 
Example 28
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 29
Project: StormOnline   Author: stormsha   File: dashboard.py    License: Apache License 2.0 5 votes vote down vote up
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) 
Example 30
Project: StormOnline   Author: stormsha   File: chart.py    License: Apache License 2.0 5 votes vote down vote up
def get_chart_url(self, name, v):
        return self.model_admin_url('chart', name) + "?" + urlencode(self.list_params)