def buildRequestUrl(self):
     qd = QueryDict("", mutable=True)
     for key in Quattro.QUERY_STRING_KEYS:
         value = getattr(self, key, None)
         if value:
             qd[key] = value
     return Quattro.QUATTRO_URL + "?" + qd.urlencode()
Beispiel #2
0
    def get_form_kwargs(self):
        
        kwargs = super(UpdateFormEntryView, self).get_form_kwargs()

        #ADD REFERNCE TO FORM OBJECT AND FIELD DATA
        kwargs['form_schema'] = self.object
        kwargs['request'] = self.request
        kwargs['instance'] = self.form_entry_object
        

        if self.request.method in ('POST', 'PUT'):
            
            kwargs.update({
                'data': self.request.POST,
                'files': self.request.FILES,
            })
            
        else:
            
            data = {'form_schema':self.object.pk}
            fields = self.form_entry_object.get_entries()
            for field in fields:
                key = self.form_class.form_field_prefix+field.form_field.slug
                data[key] = field.decompressed_value

            qdict = QueryDict('', mutable=True)
            qdict.update(data)
            kwargs['data'] = qdict

        

        return kwargs
Beispiel #3
0
 def test_login_url_with_querystring(self):
     login_url = '/login/?pretty=1'
     login_required_url = self.get_login_required_url(login_url)
     querystring = QueryDict('pretty=1', mutable=True)
     querystring['next'] = '/login_required/'
     self.assertEqual(login_required_url, 'http://testserver/login/?%s' %
                      querystring.urlencode('/'))
Beispiel #4
0
def next_redirect(request, default='/', additional_params=None,
                  next_key='next', redirect_url=None, canvas=False):
    from django_facebook import settings as facebook_settings
    if facebook_settings.FACEBOOK_DEBUG_REDIRECTS:
        return HttpResponse(
            '<html><head></head><body><div>Debugging</div></body></html>')
    from django.http import HttpResponseRedirect
    if not isinstance(next_key, (list, tuple)):
        next_key = [next_key]

    # get the redirect url
    if not redirect_url:
        for key in next_key:
            redirect_url = request.REQUEST.get(key)
            if redirect_url:
                break
        if not redirect_url:
            redirect_url = default

    if additional_params:
        query_params = QueryDict('', True)
        query_params.update(additional_params)
        seperator = '&' if '?' in redirect_url else '?'
        redirect_url += seperator + query_params.urlencode()

    if canvas:
        return CanvasRedirect(redirect_url)
    
    return HttpResponseRedirect(redirect_url)
    def get(self, request):
        data = self.get_data(request)
        code = self.get_data(request, "code")
        error = self.get_data(request, "error")
        client = self.get_data(request, "client")

        redirect_uri = data.get('redirect_uri', None) or client.redirect_uri

        parsed = urlparse.urlparse(redirect_uri)

        query = QueryDict('', mutable=True)

        if 'state' in data:
            query['state'] = data['state']

        if error is not None:
            query.update(error)
        elif code is None:
            query['error'] = 'access_denied'
        else:
            query['code'] = code

        parsed = parsed[:4] + (query.urlencode(), '')

        redirect_uri = urlparse.ParseResult(*parsed).geturl()

        self.clear_data(request)

        return HttpResponseRedirect(redirect_uri)
Beispiel #6
0
def _get_nodes(request, graph_id, query={}):
	"""

	Query Parameters
	----------
	graph_id : string
		Unique ID of the graph.
	limit : integer
		Number of entities to return. Default value is 20.
	offset : integer
		Offset the list of returned entities by this number. Default value is 0.
	names : list of strings
		Search for groups with given names. In order to search for groups with given name as a substring, wrap the name with percentage symbol. For example, %xyz% will search for all groups with xyz in their name.
	labels : list of strings
		Search for groups with given labels. In order to search for groups with given label as a substring, wrap the label with percentage symbol. For example, %xyz% will search for all groups with xyz in their label.
	order : string
		Defines the column sort order, can only be 'asc' or 'desc'.
	sort : string
		Defines which column will be sorted.


	Parameters
	----------
	request : object
		HTTP GET Request.

	Returns
	-------
	total : integer
		Number of nodes matching the request.
	nodes : List of nodes.
		List of Node Objects with given limit and offset.

	Raises
	------

	Notes
	------

	"""

	authorization.validate(request, permission='GRAPH_READ', graph_id=graph_id)

	querydict = QueryDict('', mutable=True)
	querydict.update(query)
	query = querydict

	total, nodes_list = graphs.search_nodes(request,
	                                        graph_id=graph_id,
	                                        names=query.getlist('names[]', None),
	                                        labels=query.getlist('labels[]', None),
	                                        limit=query.get('limit', 20),
	                                        offset=query.get('offset', 0),
	                                        order=query.get('order', 'desc'),
	                                        sort=query.get('sort', 'name'))

	return {
		'total': total,
		'nodes': [utils.serializer(node) for node in nodes_list]
	}
Beispiel #7
0
    def _wrapped_view(request, gid, *args, **kwargs):
        if not canEdit(request, gid):
            url = reverse("maps:auth", kwargs={"gid":gid})
            fwd = QueryDict('p=%s' % request.get_full_path())
            return HttpResponseRedirect("%s?%s" % (url, fwd.urlencode()))

        return view(request, gid, *args, **kwargs)
Beispiel #8
0
    def _verify_postback(self):
        # ### Now we don't really care what result was, just whether a flag was set or not.
        from paypal.standard.pdt.forms import PayPalPDTForm

        response_list = self.response.split('\n')
        response_dict = {}
        for i, line in enumerate(response_list):
            unquoted_line = unquote_plus(line).strip()
            if i == 0:
                self.st = unquoted_line
            else:
                if self.st != "SUCCESS":
                    self.set_flag(line)
                    break
                try:
                    if not unquoted_line.startswith(' -'):
                        k, v = unquoted_line.split('=')
                        response_dict[k.strip()] = v.strip()
                except ValueError:
                    pass

        qd = QueryDict('', mutable=True)
        qd.update(response_dict)
        qd.update(dict(ipaddress=self.ipaddress, st=self.st, flag_info=self.flag_info, flag=self.flag,
                       flag_code=self.flag_code))
        pdt_form = PayPalPDTForm(qd, instance=self)
        pdt_form.save(commit=False)
    def test_expired_course(self):
        """
        Ensure that a user accessing an expired course sees a redirect to
        the student dashboard, not a 404.
        """
        CourseDurationLimitConfig.objects.create(enabled=True, enabled_as_of=datetime(2010, 1, 1))
        course = CourseFactory.create(start=THREE_YEARS_AGO)
        url = course_home_url(course)

        for mode in [CourseMode.AUDIT, CourseMode.VERIFIED]:
            CourseModeFactory.create(course_id=course.id, mode_slug=mode)

        # assert that an if an expired audit user tries to access the course they are redirected to the dashboard
        audit_user = UserFactory(password=self.TEST_PASSWORD)
        self.client.login(username=audit_user.username, password=self.TEST_PASSWORD)
        audit_enrollment = CourseEnrollment.enroll(audit_user, course.id, mode=CourseMode.AUDIT)
        ScheduleFactory(start=THREE_YEARS_AGO, enrollment=audit_enrollment)

        response = self.client.get(url)

        expiration_date = strftime_localized(course.start + timedelta(weeks=4), 'SHORT_DATE')
        expected_params = QueryDict(mutable=True)
        course_name = CourseOverview.get_from_id(course.id).display_name_with_default
        expected_params['access_response_error'] = 'Access to {run} expired on {expiration_date}'.format(
            run=course_name,
            expiration_date=expiration_date
        )
        expected_url = '{url}?{params}'.format(
            url=reverse('dashboard'),
            params=expected_params.urlencode()
        )
        self.assertRedirects(response, expected_url)
Beispiel #10
0
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)
Beispiel #11
0
    def _parse_response(self, response):
        """Turn the PayPal response into a dict"""
        q = QueryDict(response, encoding='UTF-8').dict()
        tmp = {}
        for k,v in q.items():
            tmp.update({k.lower(): v})
	return tmp
Beispiel #12
0
def format_preserving_redirect(request, target, get_dict=None):
  """
  If request represents an ajax or embeddable "format", tries
  to preserve that for redirects.

  Any GET params may be passed through the QueryDict get_dict,
  which should be mutable.
  """
  my_get_dict = QueryDict('', mutable=True)
  if get_dict:
    my_get_dict.update(get_dict)

  if is_jframe_request(request):
    logging.info("JFrame redirection" +  target)
    my_get_dict['format'] = 'embed'
  elif request.ajax:
    my_get_dict['format'] = 'json'

  param = my_get_dict.urlencode()
  if param:
    if '?' not in target:
      param = '?' + param
    else:
      param = '&' + param

  return HttpResponseRedirect(target + param)
 def _get_initial_query_dict(self, qdict):
     if not qdict:
         qdict = QueryDict(None, mutable=True)
     elif isinstance(qdict, QueryDict):
         qdict = qdict.copy()
     elif isinstance(qdict, basestring):
         if qdict.startswith('?'):
             qdict = qdict[1:]
         qdict = QueryDict(qdict, mutable=True)
     else:
         # Accept any old dict or list of pairs.
         try:
             pairs = qdict.items()
         except:
             pairs = qdict
         qdict = QueryDict(None, mutable=True)
         # Enter each pair into QueryDict object:
         try:
             for k, v in pairs:
                 # Convert values to unicode so that detecting
                 # membership works for numbers.
                 if isinstance(v, (list, tuple)):
                     for e in v:
                         qdict.appendlist(k,unicode(e))
                 else:
                     qdict.appendlist(k, unicode(v))
         except:
             # Wrong data structure, qdict remains empty.
             pass
     return qdict
Beispiel #14
0
    def test_single_key_value(self):
        """Test QueryDict with one key/value pair"""

        q = QueryDict("foo=bar")
        self.assertEqual(q["foo"], "bar")
        self.assertRaises(KeyError, q.__getitem__, "bar")
        self.assertRaises(AttributeError, q.__setitem__, "something", "bar")

        self.assertEqual(q.get("foo", "default"), "bar")
        self.assertEqual(q.get("bar", "default"), "default")
        self.assertEqual(q.getlist("foo"), ["bar"])
        self.assertEqual(q.getlist("bar"), [])

        self.assertRaises(AttributeError, q.setlist, "foo", ["bar"])
        self.assertRaises(AttributeError, q.appendlist, "foo", ["bar"])

        self.assertTrue(q.has_key("foo"))
        self.assertTrue("foo" in q)
        self.assertFalse(q.has_key("bar"))
        self.assertFalse("bar" in q)

        self.assertEqual(q.items(), [(u"foo", u"bar")])
        self.assertEqual(q.lists(), [(u"foo", [u"bar"])])
        self.assertEqual(q.keys(), ["foo"])
        self.assertEqual(q.values(), ["bar"])
        self.assertEqual(len(q), 1)

        self.assertRaises(AttributeError, q.update, {"foo": "bar"})
        self.assertRaises(AttributeError, q.pop, "foo")
        self.assertRaises(AttributeError, q.popitem)
        self.assertRaises(AttributeError, q.clear)
        self.assertRaises(AttributeError, q.setdefault, "foo", "bar")

        self.assertEqual(q.urlencode(), "foo=bar")
def form_validate(formclass, data, instance=None, commit=True):
    '''
    Uses a form to validate data passed in as a dictionary. See
    http://docs.djangoproject.com/en/dev/ref/forms/validation/

    Arguments:
    
        formclass
            The class of the form to use

        data
            A dictionary of data

        instance
            An existing instance to use to validate
    '''

    qd = QueryDict({}).copy()
    qd.update(data)

    form = formclass(qd, instance=instance)

    if not form.is_valid():
        raise exceptions.APIBadRequest(simplejson.dumps(form.errors))

    return form.save(commit=commit)
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']}
def sso_logout(request):
    qs = QueryDict(None, mutable=True)
    qs['callback_url'] = request.build_absolute_uri(settings.SSO_LOGOUT_CALLBACK_PATH)

    logout_url = '{0}?{1}'.format(sso_hostname('/logout'), qs.urlencode(safe='/'))

    return HttpResponseRedirect(logout_url)
Beispiel #18
0
    def rpc_call(self, request, method=None, **payload):
        """ Call REST API with RPC force.
        """
        assert method and self.separator in method, \
            "Wrong method name: {0}".format(method)

        resource_name, method = method.split(self.separator, 1)
        assert resource_name in self.api.resources, "Unknown method"

        data = QueryDict('', mutable=True)
        data.update(payload.get('data', dict()))
        data['callback'] = payload.get('callback') or request.GET.get(
            'callback') or request.GET.get('jsonp') or 'callback'
        for h, v in payload.get('headers', dict()).iteritems():
            request.META["HTTP_%s" % h.upper().replace('-', '_')] = v

        request.POST = request.PUT = request.GET = data
        delattr(request, '_request')
        request.method = method.upper()
        request.META['CONTENT_TYPE'] = 'application/x-www-form-urlencoded'
        params = payload.pop('params', dict())
        response = self.api.call(resource_name, request, **params)
        response.finaly = True
        assert response.status_code == 200, response.content
        return response
Beispiel #19
0
 def test_add(self):
     """
     Test adding a plugin to a *PAGE*.
     """
     page, placeholder, superuser, staff = self.get_data()
     get_data = {
         'plugin_type': "TextPlugin",
         'plugin_language': settings.LANGUAGES[0][0],
         'placeholder_id': page.placeholders.get(slot="body").pk,
     }
     post_data = {}
     self.assertEqual(CMSPlugin.objects.count(), 0)
     # log the user out and post the plugin data to the cms add-plugin URL.
     self.client.logout()
     add_url = URL_CMS_PLUGIN_ADD + '?' + urlencode(get_data)
     response = self.client.post(add_url, post_data)
     # since the user is not logged in, they should be prompted to log in.
     self.assertEqual(response.status_code, 302)
     querystring = QueryDict('', mutable=True)
     querystring['next'] = add_url
     expected_url = '/{lang}/admin/login/?{next}'.format(
         lang=settings.LANGUAGES[0][0],
         next=querystring.urlencode(safe='/')
     )
     self.assertRedirects(response, expected_url)
     self.assertEqual(CMSPlugin.objects.count(), 0)
     # now log a staff user without permissions in and do the same as above.
     self.client.login(username=getattr(staff, get_user_model().USERNAME_FIELD),
                       password=getattr(staff, get_user_model().USERNAME_FIELD))
     response = self.client.post(add_url, post_data)
     # the user is logged in and the security check fails, so it should 403.
     self.assertEqual(response.status_code, 403)
     self.assertEqual(CMSPlugin.objects.count(), 0)
Beispiel #20
0
 def test_mutable_copy(self):
     """A copy of a QueryDict is mutable."""
     q = QueryDict().copy()
     with self.assertRaises(KeyError):
         q.__getitem__("foo")
     q["name"] = "john"
     self.assertEqual(q["name"], "john")
Beispiel #21
0
    def test_single_key_value(self):
        """Test QueryDict with one key/value pair"""

        q = QueryDict('foo=bar')
        self.assertEqual(q['foo'], 'bar')
        self.assertRaises(KeyError, q.__getitem__, 'bar')
        self.assertRaises(AttributeError, q.__setitem__, 'something', 'bar')

        self.assertEqual(q.get('foo', 'default'), 'bar')
        self.assertEqual(q.get('bar', 'default'), 'default')
        self.assertEqual(q.getlist('foo'), ['bar'])
        self.assertEqual(q.getlist('bar'), [])

        self.assertRaises(AttributeError, q.setlist, 'foo', ['bar'])
        self.assertRaises(AttributeError, q.appendlist, 'foo', ['bar'])

        self.assertTrue(q.has_key('foo'))
        self.assertTrue('foo' in q)
        self.assertFalse(q.has_key('bar'))
        self.assertFalse('bar' in q)

        self.assertEqual(q.items(), [(u'foo', u'bar')])
        self.assertEqual(q.lists(), [(u'foo', [u'bar'])])
        self.assertEqual(q.keys(), ['foo'])
        self.assertEqual(q.values(), ['bar'])
        self.assertEqual(len(q), 1)

        self.assertRaises(AttributeError, q.update, {'foo': 'bar'})
        self.assertRaises(AttributeError, q.pop, 'foo')
        self.assertRaises(AttributeError, q.popitem)
        self.assertRaises(AttributeError, q.clear)
        self.assertRaises(AttributeError, q.setdefault, 'foo', 'bar')

        self.assertEqual(q.urlencode(), 'foo=bar')
Beispiel #22
0
 def test_delete_ph(self):
     page, placeholder, superuser, staff = self.get_data()
     plugin = add_plugin(placeholder, 'TextPlugin', 'en', body='body')
     plugin_data = {
         'plugin_id': plugin.pk,
     }
     plugin = self.reload(plugin)
     self.assertEqual(plugin.body, 'body')
     endpoint = self.get_delete_plugin_uri(plugin, container=Example1)
     # log the user out and try to remove a plugin using PlaceholderAdmin
     self.client.logout()
     response = self.client.post(endpoint, plugin_data)
     # since the user is not logged in, they should be prompted to log in.
     self.assertEqual(response.status_code, 302)
     querystring = QueryDict('', mutable=True)
     querystring['next'] = endpoint
     expected_url = '/{lang}/admin/login/?{next}'.format(
         lang=settings.LANGUAGES[0][0],
         next=querystring.urlencode(safe='/')
     )
     self.assertRedirects(response, expected_url)
     self.assertEqual(CMSPlugin.objects.count(), 1)
     # now log a staff user without permissions in and do the same as above.
     self.client.login(username=getattr(staff, get_user_model().USERNAME_FIELD),
                       password=getattr(staff, get_user_model().USERNAME_FIELD))
     response = self.client.post(endpoint, plugin_data)
     # the user is logged in and the security check fails, so it should 403.
     self.assertEqual(response.status_code, 403)
     self.assertEqual(CMSPlugin.objects.count(), 1)
Beispiel #23
0
def get_job_detail_breadbox(request, job_id):
    job = get_job(request, job_id)
    if not job:
        return {}

    site_config = get_site_config(request)

    breadbox = helpers.job_breadcrumbs(job, site_config.browse_company_show)

    query_string = get_query_string(request)
    if query_string:
        # Append the query_path to all of the exising urls
        for field in breadbox:
            path = breadbox[field].get('path', '/jobs/')
            path_and_query_string = "%s?%s" % (path, query_string)
            new_url = (path_and_query_string if query_string
                       else breadbox[field]['path'])
            breadbox[field]['path'] = new_url

        # Create a new path for title and moc query string values
        # from the job information.
        fields = ['title', 'city']
        path = ''
        for field in fields:
            slab = getattr(job, '%s_slab' % field)
            path = "%s%s/" % (path, slab.split("::")[0])
        for field in ['q', 'moc']:
            if request.GET.get(field, None):
                breadbox[field] = {}
                qs = QueryDict(query_string).copy()
                del qs[field]
                breadbox[field]['path'] = "/%s?%s" % (path, qs.urlencode())
                breadbox[field]['display'] = request.GET.get(field)

    return breadbox
Beispiel #24
0
 def test_edit(self):
     """
     Test editing a *PAGE* plugin
     """
     page, placeholder, superuser, staff = self.get_data()
     # create the plugin using a superuser
     plugin = add_plugin(placeholder, 'TextPlugin', 'en', body='body')
     plugin_data = {
         'plugin_id': plugin.pk,
         'body': 'newbody',
     }
     self.assertEqual(plugin.body, 'body') # check the body is as expected.
     # log the user out, try to edit the plugin
     self.client.logout()
     endpoint = self.get_change_plugin_uri(plugin)
     response = self.client.post(endpoint, plugin_data)
     # since the user is not logged in, they should be prompted to log in.
     self.assertEqual(response.status_code, 302)
     querystring = QueryDict('', mutable=True)
     querystring['next'] = endpoint
     expected_url = '/{lang}/admin/login/?{next}'.format(
         lang=settings.LANGUAGES[0][0],
         next=querystring.urlencode(safe='/')
     )
     self.assertRedirects(response, expected_url)
     plugin = self.reload(plugin)
     self.assertEqual(plugin.body, 'body')
     # now log a staff user without permissions in and do the same as above.
     self.client.login(username=getattr(staff, get_user_model().USERNAME_FIELD),
                       password=getattr(staff, get_user_model().USERNAME_FIELD))
     response = self.client.post(endpoint, plugin_data)
     # the user is logged in and the security check fails, so it should 403.
     self.assertEqual(response.status_code, 403)
     plugin = self.reload(plugin)
     self.assertEqual(plugin.body, 'body')
Beispiel #25
0
def get_oauth_url(request, scope, redirect_uri=None):
    '''
    Returns the oauth url for the given request and scope
    Request maybe shouldnt be tied to this function, but for now it seems 
    rather ocnvenient
    '''
    from django_facebook import settings as facebook_settings
    scope = parse_scope(scope)
    query_dict = QueryDict('', True)
    query_dict['scope'] = ','.join(scope)
    query_dict['client_id'] = facebook_settings.FACEBOOK_APP_ID
    redirect_uri = redirect_uri or request.build_absolute_uri()

    #set attempt=1 to prevent endless redirect loops
    if 'attempt=1' not in redirect_uri:
        if '?' not in redirect_uri:
            redirect_uri += '?attempt=1'
        else:
            redirect_uri += '&attempt=1'
        
    if ('//localhost' in redirect_uri or '//127.0.0.1' in redirect_uri) and settings.DEBUG:
        raise ValueError, 'Facebook checks the domain name of your apps. Therefor you cannot run on localhost. Instead you should use something like local.fashiolista.com. Replace Fashiolista with your own domain name.'
    query_dict['redirect_uri'] = redirect_uri
    url = 'https://www.facebook.com/dialog/oauth?'
    url += query_dict.urlencode()
    return url, redirect_uri
Beispiel #26
0
    def process_request(self, request):
        if 'application/json' in request.META.get('CONTENT_TYPE', ''):
            # load the json data
            data = json.loads(request.body)
            # for consistency sake, we want to return
            # a Django QueryDict and not a plain Dict.
            # The primary difference is that the QueryDict stores
            # every value in a list and is, by default, immutable.
            # The primary issue is making sure that list values are
            # properly inserted into the QueryDict.  If we simply
            # do a q_data.update(data), any list values will be wrapped
            # in another list. By iterating through the list and updating
            # for each value, we get the expected result of a single list.
            q_data = QueryDict('', mutable=True)
            for key, value in data.iteritems():
                print value
                if isinstance(value, list):
                    # need to iterate through the list and update
                    # so that the list does not get wrapped in an
                    # additional list.
                    for x in value:
                        q_data.update({key: x})
                else:
                    q_data.update({key: value})

            if request.method == 'GET':
                request.GET = q_data

            if request.method == 'POST':
                request.POST = q_data

        return None
Beispiel #27
0
 def test_https_login_url(self):
     login_url = 'https:///login/'
     login_required_url = self.get_login_required_url(login_url)
     querystring = QueryDict('', mutable=True)
     querystring['next'] = 'http://testserver/login_required/'
     self.assertEqual(login_required_url,
                      '%s?%s' % (login_url, querystring.urlencode('/')))
Beispiel #28
0
    def render_change_form(self, request, context, add=False, change=False,
                           form_url='', obj=None):
        lang_code = self._language(request)
        lang = get_language_name(lang_code)
        available_languages = self.get_available_languages(obj)

        context.update({
            'title': '%s (%s)' % (context['title'], lang),
            'current_is_translated': lang_code in available_languages,
            'allow_deletion': len(available_languages) > 1,
            'language_tabs': self.get_language_tabs(request, available_languages),
            'base_template': self.get_change_form_base_template(),
        })

        # Ensure form action url carries over tab language
        qs_language = request.GET.get('language')
        if qs_language:
            form_url = urlparse(form_url or request.get_full_path())
            query = QueryDict(form_url.query, mutable=True)
            if 'language' not in query:
                query['language'] = qs_language
            form_url = form_url._replace(query=query.urlencode()).geturl()

        return super(TranslatableAdmin, self).render_change_form(request,
                                                                  context,
                                                                  add, change,
                                                                  form_url, obj)
Beispiel #29
0
 def test_mutable_copy(self):
     """A copy of a QueryDict is mutable."""
     q = QueryDict().copy()
     with self.assertRaises(KeyError):
         q.__getitem__("foo")
     q['name'] = 'john'
     self.assertEqual(q['name'], 'john')
Beispiel #30
0
def get_oauth_url(request, scope, redirect_uri=None, extra_params=None):
    '''
    Returns the oauth url for the given request and scope
    Request maybe shouldnt be tied to this function, but for now it seems
    rather ocnvenient
    '''
    from django_facebook import settings as facebook_settings
    scope = parse_scope(scope)
    query_dict = QueryDict('', True)
    query_dict['scope'] = ','.join(scope)
    query_dict['client_id'] = facebook_settings.FACEBOOK_APP_ID
    redirect_uri = redirect_uri or request.build_absolute_uri()
    current_uri = redirect_uri

    # set attempt=1 to prevent endless redirect loops
    if 'attempt=1' not in redirect_uri:
        if '?' not in redirect_uri:
            redirect_uri += '?attempt=1'
        else:
            redirect_uri += '&attempt=1'

    query_dict['redirect_uri'] = redirect_uri
    oauth_url = 'https://www.facebook.com/dialog/oauth?'
    oauth_url += query_dict.urlencode()
    return oauth_url, current_uri, redirect_uri