def frontend_url(request, url=None, back_link=None, absolute=True): """Construct an url for a frontend view. :keyword back: type of the back link to be added to the query string - here: link to the current request page - here_if_none: add link only if there is no `back` parameter :keyword absolute: construct absolute url, including host name namespace = self.ns_map[task.process.flow_class] return frontend_url( self.request, flow_url(namespace, task, 'index', user=request.user), back='here') """ params = QueryDict(mutable=True) for key, value in six.iterlists(request.GET): if not key.startswith('datatable-') and key != '_': params.setlist(key, value) if back_link == 'here_if_none' and 'back' in params: # Do nothing pass elif back_link is not None: if params: back = "{}?{}".format(quote(request.path), quote(params.urlencode())) else: back = "{}".format(quote(request.path)) params['back'] = back if url is not None: location = '{}?{}'.format(url, params.urlencode()) return request.build_absolute_uri(location) if absolute else location else: return params.urlencode()
def encode_data(data, content_type=None): # type: (Any, Optional[text_type]) -> Any # content_type of None means django's test client's default content type # if content_type is None, return data as it is if content_type is None: if data is None: return {} else: return data elif content_type.startswith('application/json'): if data is None: raise BadDataError("empty_json") try: return force_text(json.dumps(data, cls=DjangoJSONEncoder)) except ValueError: raise BadDataError("invalid_format") elif content_type.startswith(FORM_CONTENT_TYPE): if data is None or data == "": return "" elif isinstance(data, dict): form_data = QueryDict(mutable=True) for key, value in six.iteritems(data): if isinstance(value, Sequence) and not (isinstance(value, text_type)): form_data.setlist(str(key), value) else: form_data[key] = value return form_data.urlencode() else: raise BadDataError("invalid_format") else: raise ContentTypeError(content_type)
def create_next_domains_url(path, scheme="http", domain="", query_params={}, clone_domains=()): """ handy function to create an url with clone domains querystring""" # Set the correct params (clones and redirect url) # Small hack to create automatically the url :P params = QueryDict(mutable=True) for k, v in query_params.items(): params[k] = v if len(clone_domains) > 0: params.setlist('clone-domains', clone_domains) url = urllib.parse.ParseResult( scheme=scheme, netloc=domain, path=path, params="", query=params.urlencode(), fragment="", ) return url.geturl()
def email_file(self, f: File, size: int, url: str): template_name = 'aristotle_mdr/email/download.html' context: Dict[str, Union[str, bool]] = { 'item_names': ', '.join([i.name for i in self.items]), 'download_url': url } # Send email with a link to the file and link to regenerate storage = self.get_storage() if hasattr(storage, 'querystring_expire'): expire_seconds = storage.querystring_expire context['expire_time'] = format_seconds(expire_seconds) # Build url to regenerate download query = QueryDict(mutable=True) query.setlist('items', self.item_ids) regenerate_url = '{host}{url}?{qstring}'.format( host=self.options['CURRENT_HOST'], url=reverse('aristotle:download_options', args=[self.download_type]), qstring=query.urlencode()) # Update context context.update({'attached': False, 'regenerate_url': regenerate_url}) email = EmailMessage( 'Aristotle Download', render_to_string(template_name, context), to=[self.user.email], ) email.content_subtype = 'html' # Sets the mime type of the body to text/html email.send(fail_silently=True)
def urlencode(self): """Return a URL encoded GET string""" def convert_date(date): """Get date into correct format""" if date is None: return "" else: return date.strftime("%m/%d/%Y") params = QueryDict("", mutable=True) min_pages = self.min_pages if self.min_pages is not None else "" min_date = convert_date(self.min_date) max_date = convert_date(self.max_date) params.update( { "q": self.query, "status": self.status, "has_embargo": self.embargo, "has_crowdfund": self.exclude_crowdfund, "minimum_pages": min_pages, "date_range_0": min_date, "date_range_1": max_date, "search_title": self.title, } ) params.setlist("user", self.users.values_list("pk", flat=True)) params.setlist("agency", self.agencies.values_list("pk", flat=True)) params.setlist("projects", self.projects.values_list("pk", flat=True)) params.setlist("tags", self.tags.values_list("pk", flat=True)) params.setlist( "jurisdiction", [str(j) for j in self.searchjurisdiction_set.all()] ) return params.urlencode()
def encode_data(data, content_type=None): # type: (Any, Optional[text_type]) -> Any # content_type of None means django's test client's default content type # if content_type is None, return data as it is if content_type is None: if data is None: return {} else: return data elif content_type.startswith('application/json'): if data is None: raise BadDataError("empty_json") try: return force_text(json.dumps(data, cls=DjangoJSONEncoder)) except ValueError: raise BadDataError("invalid_format") elif content_type.startswith(FORM_CONTENT_TYPE): if data is None or data == "": return "" elif isinstance(data, dict): form_data = QueryDict(mutable=True) for key, value in six.iteritems(data): if isinstance(value, Sequence) and not(isinstance(value, text_type)): form_data.setlist(str(key), value) else: form_data[key] = value return form_data.urlencode() else: raise BadDataError("invalid_format") else: raise ContentTypeError(content_type)
def suggest_new_example(logic, assume_commutative=False): log_eng = LogicEngine() expr = ~log_eng.parse_logic(logic, convert_to_converse=True) if assume_commutative: expr = expr.subs( 'x_1', True) # We want to remove commutativity from consideration modls = satisfiable(expr, all_models=True) results = [] for modl in modls: has = [k.name for k, v in modl.items() if v is True] lacks = [k.name for k, v in modl.items() if v is False] has = map(lambda x: x.replace('x', 'H'), has) lacks = map(lambda x: x.replace('x', 'L'), lacks) terms = list(map(lambda x: x.replace('_', ''), has)) terms.extend(map(lambda x: x.replace('_', ''), lacks)) narrow, _ = ring_search(terms) if len(narrow) > 0: continue terms = mirror_search_terms(terms) narrow, _ = ring_search(terms) if len(narrow) > 0: continue has = [item[1:] for item in terms if item.startswith('H')] lacks = [item[1:] for item in terms if item.startswith('L')] has_readable = [term_to_readable(x) for x in has] lacks_readable = [term_to_readable(x) for x in lacks] qd = QueryDict(mutable=True) qd.setlist('H', has) qd.setlist('L', lacks) results.append((has_readable, lacks_readable, '{}?{}'.format(reverse('results'), qd.urlencode()))) return results
def urlencode(self): """Return a URL encoded GET string""" def convert_date(date): """Get date into correct format""" if date is None: return '' else: return date.strftime('%m/%d/%Y') params = QueryDict('', mutable=True) min_pages = self.min_pages if self.min_pages is not None else '' min_date = convert_date(self.min_date) max_date = convert_date(self.max_date) params.update({ 'q': self.query, 'status': self.status, 'has_embargo': self.embargo, 'has_crowdfund': self.exclude_crowdfund, 'minimum_pages': min_pages, 'date_range_0': min_date, 'date_range_1': max_date, 'search_title': self.title, }) params.setlist('user', self.users.values_list('pk', flat=True)) params.setlist('agency', self.agencies.values_list('pk', flat=True)) params.setlist('projects', self.projects.values_list('pk', flat=True)) params.setlist('tags', self.tags.values_list('pk', flat=True)) params.setlist( 'jurisdiction', [unicode(j) for j in self.searchjurisdiction_set.all()], ) return params.urlencode()
def get_toolbar(self, request): form = RequestToolbarForm(request.GET or None) if not form.is_valid(): return HttpResponseBadRequest('Invalid parameters') form_data = form.cleaned_data cms_path = form_data.get('cms_path') or request.path_info origin_url = urlparse(cms_path) attached_obj = form_data.get('attached_obj') current_page = get_page_from_request(request, use_path=origin_url.path, clean_path=True) if attached_obj and current_page and not (attached_obj == current_page): return HttpResponseBadRequest( 'Generic object does not match current page') data = QueryDict(query_string=origin_url.query, mutable=True) placeholders = request.GET.getlist("placeholders[]") if placeholders: data.setlist('placeholders[]', placeholders) request = copy.copy(request) request.GET = data request.current_page = current_page request.toolbar = CMSToolbar(request, request_path=origin_url.path) request.toolbar.set_object(attached_obj or current_page) return HttpResponse(request.toolbar.render())
def dict_to_querydict(dict_data): qdict = QueryDict('', mutable=True) for key, value in dict_data.items(): if isinstance(value, list): qdict.setlist(key, value) else: qdict[key] = value return qdict
def to_internal_value(self, data: QueryDict): value = str(data.get('items')) items_list = list(map(int, value.replace(" ", "").split(","))) data.setlist('items', items_list) values = super().to_internal_value(data) values['whatsapp'] = f"55{data['whatsapp']}" return values
def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) cancel = self.request.GET.get("cancel", False) request_get = self.request.GET.copy() if cancel: request_get = QueryDict() if not request_get: # Create a mutable QueryDict object, default is immutable request_get = QueryDict(mutable=True) request_get.setlist("region", [self.object]) self.filter = self.filter_class(request_get) chapters = Chapter.objects.exclude(active=False) if self.filter.is_bound and self.filter.is_valid(): region_slug = self.filter.form.cleaned_data["region"] region = Region.objects.filter(slug=region_slug).first() active_chapters = Chapter.objects.exclude(active=False) if region: chapters = active_chapters.filter(region__in=[region]) elif region_slug == "candidate_chapter": chapters = active_chapters.filter(candidate_chapter=True) all_chapter_advisors = User.objects.none() for chapter in chapters: all_chapter_advisors = chapter.advisors | all_chapter_advisors self.filter = self.filter_class(request_get, queryset=all_chapter_advisors) self.filter.form.helper = self.formhelper_class() email_list = ", ".join( [x[0] for x in self.filter.qs.values_list("email").distinct()]) all_chapter_advisors = combine_annotations(self.filter.qs) self.filter.form.fields["chapter"].queryset = chapters admin = self.request.user.is_superuser table = UserTable( data=all_chapter_advisors, natoff=True, admin=admin, extra_columns=[ ( "chapter", tables.LinkColumn("chapters:detail", args=[A("chapter.slug")]), ), ("chapter.region", tables.Column("Region")), ("chapter.school", tables.Column("School")), ], ) table.exclude = ( "badge_number", "major", "graduation_year", "current_status", "role_end", ) RequestConfig(self.request, paginate={"per_page": 50}).configure(table) context["table"] = table context["filter"] = self.filter context["email_list"] = email_list context["view_type"] = "Advisors" return context
def test_county_select_persists_after_session_update(self): response = self.client.fill_form( reverse('intake-apply'), counties=['alameda', 'contracosta']) request = response.wsgi_request qdict = QueryDict('', mutable=True) qdict.setlist('hello', ['world']) utils.save_form_data_to_session( request, ApplicantFormViewBase.session_key, qdict) form_data = self.client.session.get(ApplicantFormViewBase.session_key) self.assertListEqual(['alameda', 'contracosta'], form_data['counties'])
def get_form_data_from_session(request, session_key): """Gets a dictionary from the session based on a key and converts each key, list pair into a mutable QueryDict so that it can be processed by a form as if it were post data """ raw_dict = request.session.get(session_key, {}) qdict = QueryDict('', mutable=True) for key, items in raw_dict.items(): qdict.setlist(key, items) return qdict
def test_with_project_data_slug(self): report_slugs = ['project_data'] q_dict_get = QueryDict('', mutable=True) q_dict_get.setlist('case_list_filter', report_slugs) self.request.GET = q_dict_get data = CaseListReport(self.request, domain=self.domain).es_results['hits'].get( 'hits', []) expected_case_ids = ['id-1', 'id-2', 'id-3', 'id-5'] queried_case_ids = [case['_id'] for case in data] self.assertCountEqual(expected_case_ids, queried_case_ids)
def test_county_select_persists_after_session_update(self): response = self.client.fill_form( reverse('intake-apply'), counties=['alameda', 'contracosta'], confirm_county_selection='yes') request = response.wsgi_request qdict = QueryDict('', mutable=True) qdict.setlist('hello', ['world']) utils.save_form_data_to_session( request, ApplicantFormViewBase.session_key, qdict) form_data = self.client.session.get(ApplicantFormViewBase.session_key) self.assertListEqual(['alameda', 'contracosta'], form_data['counties'])
def get_form(self): page = self.get_page() form_class = page.get_edit_handler().get_form_class(page._meta.model) parent_page = page.get_parent().specific post_data_dict, timestamp = self.request.session[self.session_key] # convert post_data_dict back into a QueryDict post_data = QueryDict('', mutable=True) for k, v in post_data_dict.items(): post_data.setlist(k, v) return form_class(post_data, instance=page, parent_page=parent_page)
def get_form_data_from_session(request, session_key): """Gets a dictionary from the session based on a key and converts each key, list pair into a mutable QueryDict so that it can be processed by a form as if it were post data """ raw_dict = request.session.get(session_key, {}) qdict = QueryDict('', mutable=True) for key, items in raw_dict.items(): if not isinstance(items, list): items = [items] qdict.setlist(key, items) return qdict
def make_url(to, args=(), kwargs={}, keep_params=False, params=None, append=None, request=None, include=None, exclude=None, fragment=None, absolute=False, resolve=True): '''Build an URL from a relative or absolute path, a model instance, a view name or view function. If you pass a request you can ask to keep params from it, exclude some of them or include only a subset of them. You can set parameters or append to existing one. ''' if resolve: url = resolve_url(to, *args, **kwargs) else: url = to scheme, netloc, path, query_string, o_fragment = urlparse.urlsplit(url) url = urlparse.urlunsplit((scheme, netloc, path, '', '')) fragment = fragment or o_fragment # Django < 1.6 compat, query_string is not optional url_params = QueryDict(query_string=query_string, mutable=True) if keep_params: assert request is not None, 'missing request' for key, value in request.GET.iteritems(): if exclude and key in exclude: continue if include and key not in include: continue url_params.setlist(key, request.GET.getlist(key)) if params: for key, value in params.iteritems(): if isinstance(value, (tuple, list)): url_params.setlist(key, value) else: url_params[key] = value if append: for key, value in append.iteritems(): if isinstance(value, (tuple, list)): url_params.extend({key: value}) else: url_params.appendlist(key, value) if url_params: url += '?%s' % url_params.urlencode(safe='/') if fragment: url += '#%s' % fragment if absolute: if request: url = request.build_absolute_uri(url) else: raise TypeError('make_url() absolute cannot be used without request') # URL must be ASCII, always return url.encode('ascii')
def test_clone_url(self): start_host = settings.JWT_COOKIE_CLONE_DOMAINS_ENDPOINT[0] self.client = Client(SERVER_NAME=start_host, HTTP_HOST=start_host) # Create a token params = QueryDict(mutable=True) params[settings.REDIRECT_URL_VALID_PARAMS[0]] = "http://google.com" clone_domains = settings.JWT_COOKIE_CLONE_DOMAINS_ENDPOINT params.setlist('clone-domains', clone_domains) jwt_token = jwt_utils.create_jwt(self.user) url_path = reverse('auth:clone-cookie', kwargs={'token': jwt_token}) url = urllib.parse.ParseResult( scheme="", netloc="", path=url_path, params="", query=params.urlencode(), fragment="", ) resp = self.client.get(url.geturl(), follow=True) self.assertEqual(200, resp.status_code) # Check cloning redirects for k, i in enumerate(resp.redirect_chain[:-1]): clone_domains = list(settings.JWT_COOKIE_CLONE_DOMAINS_ENDPOINT) params = QueryDict(mutable=True) params[settings.REDIRECT_URL_VALID_PARAMS[0]] = "http://google.com" params.setlist('clone-domains', clone_domains[k + 1:]) clone_domains = clone_domains[k:] if len(clone_domains) > 0: next_host = clone_domains[0] else: next_host = "" url = urllib.parse.ParseResult( scheme="http", netloc=next_host, path=url_path, params="", query=params.urlencode(), fragment="", ) # Final redirect (redirect uri) self.assertEqual(302, resp.redirect_chain[-1][1]) self.assertEqual(params[settings.REDIRECT_URL_VALID_PARAMS[0]], resp.redirect_chain[-1][0])
def test_clone_url(self): start_host = settings.JWT_COOKIE_CLONE_DOMAINS_ENDPOINT[0] self.client = Client(SERVER_NAME=start_host, HTTP_HOST=start_host) # Create a token params = QueryDict(mutable=True) params[settings.REDIRECT_URL_VALID_PARAMS[0]] = "http://google.com" clone_domains = settings.JWT_COOKIE_CLONE_DOMAINS_ENDPOINT params.setlist('clone-domains', clone_domains) jwt_token = jwt_utils.create_jwt(self.user) url_path = reverse('auth:clone-cookie', kwargs={'token': jwt_token}) url = urllib.parse.ParseResult( scheme="", netloc="", path=url_path, params="", query=params.urlencode(), fragment="", ) resp = self.client.get(url.geturl(), follow=True) self.assertEqual(200, resp.status_code) # Check cloning redirects for k, i in enumerate(resp.redirect_chain[:-1]): clone_domains = list(settings.JWT_COOKIE_CLONE_DOMAINS_ENDPOINT) params = QueryDict(mutable=True) params[settings.REDIRECT_URL_VALID_PARAMS[0]] = "http://google.com" params.setlist('clone-domains', clone_domains[k+1:]) clone_domains = clone_domains[k:] if len(clone_domains) > 0: next_host = clone_domains[0] else: next_host = "" url = urllib.parse.ParseResult( scheme="http", netloc=next_host, path=url_path, params="", query=params.urlencode(), fragment="", ) # Final redirect (redirect uri) self.assertEqual(302, resp.redirect_chain[-1][1]) self.assertEqual(params[settings.REDIRECT_URL_VALID_PARAMS[0]], resp.redirect_chain[-1][0])
def _scrub_GET(self,GET): """Scrubbs a QueryDict object. This function is subject to change without notice.""" OUT=QueryDict(mutable=True) # multilpe 's' get split by white space as well if 's' in GET: esses = GET.getlist('s') s=[] for ess in esses: s.extend(ess.strip().split()) if 0 < len(s): OUT.setlist('s',s) # anything else is hacking. return OUT
def get_form(self): page = self.get_page() form_class = page.get_edit_handler().get_form_class(page._meta.model) parent_page = page.get_parent().specific if self.session_key not in self.request.session: # Session key not in session, returning null form return form_class(instance=page, parent_page=parent_page) post_data_dict, timestamp = self.request.session[self.session_key] # convert post_data_dict back into a QueryDict post_data = QueryDict('', mutable=True) for k, v in post_data_dict.items(): post_data.setlist(k, v) return form_class(post_data, instance=page, parent_page=parent_page)
def read_raw_data(self, request): # convert the data into the correct format and add # it as POST variables. from django.http.request import QueryDict, MultiValueDict if not request.method in ['POST', 'PUT']: request._post, request._files = QueryDict('', encoding=request._encoding), MultiValueDict() else: # TODO multipart (files) not supported. q = QueryDict('', encoding=request._encoding).copy() d = self._raw_data_to_dict(request) for key in d.keys(): if isinstance(d[key], list): q.setlist(key, d.pop(key)) q.update(d) request.method = 'POST' request._post = q request._files = MultiValueDict()
def make_url(to, args=(), kwargs={}, keep_params=False, params=None, append=None, request=None, include=None, exclude=None, fragment=None, absolute=False): '''Build an URL from a relative or absolute path, a model instance, a view name or view function. If you pass a request you can ask to keep params from it, exclude some of them or include only a subset of them. You can set parameters or append to existing one. ''' url = resolve_url(to, *args, **kwargs) scheme, netloc, path, query_string, o_fragment = urlparse.urlsplit(url) url = urlparse.urlunsplit((scheme, netloc, path, '', '')) fragment = fragment or o_fragment # Django < 1.6 compat, query_string is not optional url_params = QueryDict(query_string=query_string, mutable=True) if keep_params: assert request is not None, 'missing request' for key, value in request.GET.iteritems(): if exclude and key in exclude: continue if include and key not in include: continue url_params.setlist(key, request.GET.getlist(key)) if params: for key, value in params.iteritems(): if isinstance(value, (tuple, list)): url_params.setlist(key, value) else: url_params[key] = value if append: for key, value in append.iteritems(): if isinstance(value, (tuple, list)): url_params.extend({key: value}) else: url_params.appendlist(key, value) if url_params: url += '?%s' % url_params.urlencode(safe='/') if fragment: url += '#%s' % fragment if absolute: if request: url = request.build_absolute_uri(url) else: raise TypeError('make_url() absolute cannot be used without request') return url
def handle_moved_contributors(self, data, **kwargs): """ Work around https://code.djangoproject.com/ticket/25139 Basically, if the user assigns a contributor who already has a contribution to a new contribution, this moves the contributor (and all the data of the new form they got assigned to) back to the original contribution. """ if data is None or 'instance' not in kwargs: return data course = kwargs['instance'] total_forms = int(data['contributions-TOTAL_FORMS']) for i in range(0, total_forms): prefix = "contributions-" + str(i) + "-" current_id = data.get(prefix + 'id', '') contributor = data.get(prefix + 'contributor', '') if contributor == '': continue # find the contribution that the contributor had before the user messed with it try: previous_id = str( Contribution.objects.get(contributor=contributor, course=course).id) except Contribution.DoesNotExist: continue if current_id == previous_id: continue # find the form with that previous contribution and then swap the contributions for j in range(0, total_forms): other_prefix = "contributions-" + str(j) + "-" other_id = data[other_prefix + 'id'] if other_id == previous_id: # swap all the data. the contribution's ids stay in place. data2 = data.copy() data = QueryDict(mutable=True) for key, value in data2.lists(): if not key.endswith('-id'): key = key.replace(prefix, '%temp%').replace( other_prefix, prefix).replace('%temp%', other_prefix) data.setlist(key, value) break return data
def handle_moved_contributors(self, data, **kwargs): """ Work around https://code.djangoproject.com/ticket/25139 Basically, if the user assigns a contributor who already has a contribution to a new contribution, this moves the contributor (and all the data of the new form they got assigned to) back to the original contribution. """ if data is None or "instance" not in kwargs: return data course = kwargs["instance"] total_forms = int(data["contributions-TOTAL_FORMS"]) for i in range(0, total_forms): prefix = "contributions-" + str(i) + "-" current_id = data.get(prefix + "id", "") contributor = data.get(prefix + "contributor", "") if contributor == "": continue # find the contribution that the contributor had before the user messed with it try: previous_id = str(Contribution.objects.get(contributor=contributor, course=course).id) except Contribution.DoesNotExist: continue if current_id == previous_id: continue # find the form with that previous contribution and then swap the contributions for j in range(0, total_forms): other_prefix = "contributions-" + str(j) + "-" other_id = data[other_prefix + "id"] if other_id == previous_id: # swap all the data. the contribution's ids stay in place. data2 = data.copy() data = QueryDict(mutable=True) for key, value in data2.lists(): if not key.endswith("-id"): key = ( key.replace(prefix, "%temp%") .replace(other_prefix, prefix) .replace("%temp%", other_prefix) ) data.setlist(key, value) break return data
def get_queryset(self, **kwargs): qs = TaskDate.dates_for_chapter(self.request.user.current_chapter) qs = super().get_queryset(other_qs=qs) cancel = self.request.GET.get("cancel", False) request_get = self.request.GET.copy() if cancel: request_get = QueryDict() if not request_get: # Create a mutable QueryDict object, default is immutable request_get = QueryDict(mutable=True) request_get.setlist("date", [""]) request_get.setlist("complete", [""]) if not cancel: if request_get.get("date", "") == "": request_get["date"] = current_year_term_slug() if request_get.get("complete", "") == "": request_get["complete"] = "0" self.filter = self.filter_class(request_get, queryset=qs) self.filter.request = self.request self.filter.form.helper = self.formhelper_class() return self.filter.qs
def search_form_request(request): """ View for the advanced search form page. """ if request.method == 'POST': form = SearchForm(request.POST) if form.is_valid(): skills = form.cleaned_data['skills_desired'] if not skills.exists(): skills = None location = form.cleaned_data['location'] tags = form.cleaned_data['tags'] if not tags.exists(): tags = None all_name = form.cleaned_data['project_name'] all_description = form.cleaned_data['description'] qdict = QueryDict(mutable=True) if skills: qdict.setlist('skills', skills) if location: qdict['location'] = location if tags: qdict.setlist('tags', tags) if all_name: qdict['all_name'] = all_name if all_description: qdict['all_description'] = all_description return HttpResponseRedirect( reverse('search-results') + "?" + qdict.urlencode()) else: form = SearchForm() return render(request, 'search_form.html', {'form': form})
class UrlHelper(object): def __init__(self, full_path): url = urlparse.urlparse(full_path) self.path = url.path self.fragment = url.fragment self.query_dict = QueryDict(url.query, mutable=True) def update_query_data(self, **kwargs): for key, val in kwargs.iteritems(): if hasattr(val, '__iter__'): self.query_dict.setlist(key, val) else: self.query_dict[key] = val def get_full_path(self, **kwargs): query_string = self.get_query_string(**kwargs) if query_string: query_string = '?' + query_string fragment = self.fragment and '#' + iri_to_uri(self.fragment) or '' return iri_to_uri(self.path) + query_string + fragment def get_query_string(self, **kwargs): return self.query_dict.urlencode(**kwargs)
class UrlHelper(object): def __init__(self, full_path): # If full_path is an UrlHelper instance, extract the full path from it if type(full_path) is UrlHelper: full_path = full_path.get_full_path() # parse the path r = urlparse.urlparse(full_path) self.path = r.path self.fragment = r.fragment self.query_dict = QueryDict(smart_bytes(r.query), mutable=True) def get_query_string(self, **kwargs): return self.query_dict.urlencode(**kwargs) def get_query_data(self): return self.query_dict def update_query_data(self, **kwargs): for key, val in kwargs.iteritems(): if hasattr(val, '__iter__'): self.query_dict.setlist(key, val) else: self.query_dict[key] = val def get_path(self): return self.path def get_full_path(self, **kwargs): query_string = self.get_query_string(**kwargs) if query_string: query_string = '?%s' % query_string fragment = self.fragment and '#%s' % iri_to_uri(self.fragment) or '' return '%s%s%s' % ( iri_to_uri(self.get_path()), query_string, fragment ) def get_full_quoted_path(self, **kwargs): return urllib.quote_plus(self.get_full_path(**kwargs), safe='/') def overload_params(self, **kwargs): for key, val in kwargs.iteritems(): uniques = set(self.query_dict.getlist(key)) uniques.add(val) self.query_dict.setlist(key, list(uniques)) def del_param(self, param): try: del self.query_dict[param] except KeyError: pass # Fail silently def del_params(self, *params, **kwargs): if not params and not kwargs: self.query = {} return if params: for param in params: self.del_param(param) if kwargs: for key, val in kwargs.iteritems(): to_keep = [x for x in self.query_dict.getlist(key) if not x.startswith(val)] self.query_dict.setlist(key, to_keep) def toggle_params(self, **params): for param, value in params.items(): value = unicode(value) if value in self.query_dict.getlist(param): self.del_params(**{param: value}) else: self.overload_params(**{param: value}) @property def hash(self): md5 = hashlib.md5() md5.update(self.get_full_path()) return md5.hexdigest() @property def query(self): return self.get_query_data() @query.setter def query(self, value): if type(value) is dict: self.query_dict = QueryDict(b'', mutable=True) self.update_query_data(**value) else: self.query_dict = QueryDict(smart_bytes(value), mutable=True) @property def query_string(self): return self.get_query_string() @query_string.setter def query_string(self, value): self.query_dict = QueryDict(smart_bytes(value), mutable=True) def __str__(self): return self.get_full_path()
def cast_to_queryDict(self, original_dict): data_query_dict = QueryDict('', mutable=True) for key, val in original_dict.items(): data_query_dict.setlist(key, val) return data_query_dict
class UrlHelper(object): def __init__(self, full_path): # If full_path is an UrlHelper instance, extract the full path from it if type(full_path) is UrlHelper: full_path = full_path.get_full_path() # parse the path r = urlparse(full_path) self.path = r.path self.fragment = r.fragment self.query_dict = QueryDict(r.query, mutable=True) def get_query_string(self, **kwargs): return self.query_dict.urlencode(**kwargs) def get_query_data(self): return self.query_dict def update_query_data(self, **kwargs): for key, val in kwargs.iteritems(): if hasattr(val, '__iter__'): self.query_dict.setlist(key, val) else: self.query_dict[key] = val def get_path(self): return self.path def get_full_path(self, **kwargs): query_string = self.get_query_string(**kwargs) if query_string: query_string = '?%s' % query_string fragment = self.fragment and '#%s' % iri_to_uri(self.fragment) or '' return '%s%s%s' % (iri_to_uri(self.get_path()), query_string, fragment) def get_full_quoted_path(self, **kwargs): return quote_plus(self.get_full_path(**kwargs), safe='/') def overload_params(self, **kwargs): for key, val in kwargs.iteritems(): uniques = set(self.query_dict.getlist(key)) uniques.add(val) self.query_dict.setlist(key, list(uniques)) def del_param(self, param): try: del self.query_dict[param] except KeyError: pass # Fail silently def del_params(self, *params, **kwargs): if not params and not kwargs: self.query = {} return if params: for param in params: self.del_param(param) if kwargs: for key, val in kwargs.iteritems(): to_keep = [ x for x in self.query_dict.getlist(key) if not x.startswith(val) ] self.query_dict.setlist(key, to_keep) def toggle_params(self, **params): for param, value in params.items(): if value in self.query_dict.getlist(param): self.del_params(**{param: value}) else: self.overload_params(**{param: value}) @property def hash(self): md5 = hashlib.md5() md5.update(self.get_full_path()) return md5.hexdigest() @property def query(self): return self.get_query_data() @query.setter def query(self, value): if type(value) is dict: self.query_dict = QueryDict('', mutable=True) self.update_query_data(**value) else: self.query_dict = QueryDict(value, mutable=True) @property def query_string(self): return self.get_query_string() @query_string.setter def query_string(self, value): self.query_dict = QueryDict(value, mutable=True) def __str__(self): return self.get_full_path()
def get_queryset(self): qs = self.model._default_manager.all() ordering = self.get_ordering() if ordering: if isinstance(ordering, str): ordering = (ordering,) qs = qs.order_by(*ordering) members = annotate_role_status( qs.filter( chapter=self.request.user.current_chapter, status__status__in=["active", "activepend", "alumnipend"], status__start__lte=TODAY_END, status__end__gte=TODAY_END, ), combine=False, ) pledges = annotate_role_status( qs.filter( chapter=self.request.user.current_chapter, status__status="pnm", status__start__lte=TODAY_END, status__end__gte=TODAY_END, ), combine=False, ) alumni = User.objects.none() if self.request.user.chapter_officer(): alumni = annotate_role_status( qs.filter( chapter=self.request.user.current_chapter, status__status__in=["alumni"], status__start__lte=TODAY_END, status__end__gte=TODAY_END, ), combine=False, ) qs = members | pledges | alumni cancel = self.request.GET.get("cancel", False) request_get = self.request.GET.copy() if cancel: request_get = QueryDict() if not request_get: # Create a mutable QueryDict object, default is immutable request_get = QueryDict(mutable=True) request_get.setlist( "current_status", [ "active", "pnm", "activepend", "alumnipend", ], ) if not cancel: current_status = request_get.get("current_status", "") if current_status == "": request_get.setlist( "current_status", [ "active", "pnm", "activepend", "alumnipend", ], ) self.filter = self.filter_class(request_get, queryset=qs, request=self.request) self.filter.form.helper = self.formhelper_class() qs = combine_annotations(self.filter.qs) return qs
def fill_form_with_dummy_data(self, form, post_data=None): import django.forms.fields import django.forms.widgets try: from captcha.widgets import ReCaptcha except ImportError: ReCaptcha = None if post_data is None: post_data = {} else: post_data = dict(post_data) fields_to_delete = [] for field in form: if field.field.required and not post_data.get(field.name): widget = field.field.widget if isinstance(widget, django.forms.widgets.Select): choices = list(widget.choices) if not choices: choices = list(field.field.choices) possible_values = [v for v, label in choices] if isinstance(widget, django.forms.widgets.SelectMultiple): value = [possible_values[0]] else: value = possible_values[0] elif isinstance(field.field, django.forms.fields.EmailField): value = "*****@*****.**" elif isinstance(widget, ReCaptcha): fields_to_delete.append(field.name) continue else: value = "Whee" post_data[field.name] = value query_dict = QueryDict('', mutable=True).copy() for key, value in post_data.iteritems(): if hasattr(value, '__iter__'): query_dict.setlist(key, value) else: query_dict.setlist(key, [value]) query_dict._mutable = False new_form = form.__class__(query_dict) for field_name in fields_to_delete: del new_form.fields[field_name] # post_data is not very useful if fields_to_delete is not empty, # because any form constructed with it won't validate, but it is # useful under some circumstances, so return it anyway. """ if fields_to_delete: post_data = None """ return new_form, post_data