def dispatch(self, *args, **kwargs): if self.request.method == "POST": data = self.request.POST elif self.request.method == "GET": data = self.request.GET elif self.request.method in ["PATCH", "PUT"]: data_dict = yaml.safe_load(self.request.body.decode()) data = QueryDict(urlencode(data_dict) if data_dict else {}) else: data = QueryDict() method = data.get('_method', self.request.method) if method: if method not in self.allowed: return HttpResponseNotAllowed( self.allowed, "Method Not Allowed (" + method + ")") if '_method' in data: data._mutable = True del data['_method'] data._mutable = False self.request.method = method self.request.META['REQUEST_METHOD'] = method setattr(self.request, method, data) return super(HttpMethodMixin, self).dispatch(*args, **kwargs)
def index(request): select_detailed_source = SelecrSourceForm() source_points = Source.objects.exclude(point=None) searchform = SearchForm(request.GET) tagcloud = Tag.objects.cloud_for_model(Resource) qs = Resource.objects.filter(enabled=True).exclude(status="rejected") query = request.GET.get("q", None) if query != None: if query != "": qs = qs.filter(search_query_set(query)) else: blankquery = True objects = [] [objects.append(item) for item in qsfiltered] # treat querystring, remove page querystring = QueryDict(request.META.get("QUERY_STRING")) # handle pagination if "page" in request.GET: pageid = request.GET.get("page") if pageid: querystring._mutable = True del querystring["page"] querystring_nopage = querystring.urlencode() else: pageid = 1 querystring_nopage = request.META.get("QUERY_STRING") paginator = Paginator(objects, CONTENT_PER_PAGE) try: page_obj = paginator.page(pageid) except TypeError: page_obj = paginator.page(1) except PageNotAnInteger: page_obj = paginator.page(1) except EmptyPage: page_obj = paginator.page(paginator.num_pages) object_list = page_obj.object_list return render_to_response("index.html", locals(), context_instance=RequestContext(request)) else: # browse mode # featured list curricular_grades = CurricularGrade.objects.filter(parent=None) featured_list = ( qs.filter( # category__code='video', thumbnails__gt=0 ) .order_by("?") .all()[0:2] ) if featured_list.count() > 0: featured_list = featured_list.all() # tags tags_to_cloud = Tag.objects.usage_for_queryset(qs, counts=True) # [0:20] calculate_cloud(tags_to_cloud, steps=5, distribution=LOGARITHMIC) query = "" # latest additions latest_additions = Resource.objects.filter(status="installed").order_by("-created")[0:5] return render_to_response("index.html", locals(), context_instance=RequestContext(request))
def next_urlencode(self): # next——新增、编辑后跳转至原页面 url = self.request.get_full_path() qd = QueryDict() qd._mutable = True qd['next'] = url return qd.urlencode()
def get_query_params(self): url = self.request.get_full_path() qd = QueryDict() qd._mutable = True qd['next'] = url query_params = qd.urlencode() return query_params
def get_refurl_context(self, name, value, attrs): attrs['data-url'] = resolve_url(self.refurl) if self.filters: query = QueryDict('', mutable=True) for k, v in self.filters.items(): if isinstance(v, (tuple, list)): v = ','.join(v) query.appendlist(k, v) query._mutable = False attrs['data-filters'] = query.urlencode() if isinstance(value, (tuple, list)): value = [x for x in value if x] context = {} context['widget'] = { 'name': name, 'is_hidden': self.is_hidden, 'required': self.is_required, 'value': self.format_value(value), 'attrs': self.build_attrs(self.attrs, attrs), 'template_name': self.template_name, } if self.allow_multiple_selected: context['widget']['attrs']['multiple'] = True if value: context['value'] = self.get_instance(value) return context
def get_url(request): url = request.get_full_path() qd = QueryDict() qd._mutable = True qd['next_page'] = url # query_params = qd.urlencode() return qd
def get_query_params(self): url = self.request.get_full_path() qd = QueryDict() qd._mutable = True qd['next'] = url # next=%2Fcrm%2Fcustomer_list%2F query_params = qd.urlencode() return query_params
def get_add_btn(self): url = self.request.get_full_path() qd = QueryDict() qd._mutable = True qd['next'] = url query_params = qd.urlencode() add_btn = '<a href="{}?{}" class="btn btn-primary btn-sm">添加</a>'.format(reverse('add_customer'), query_params) return mark_safe(add_btn), query_params
def _post(self, request, *args, **kwargs): data = request.POST if not request.POST: simple_dict = json.loads(request.body.decode('utf-8')) data = QueryDict('', mutable=True) data.update(simple_dict) upload_id = data.get('upload_id') md5 = {} if 'md5' in data: for key, value in data.get("md5").items(): md5[key] = value else: for key, value in data.dict().items(): m = re.search('(?P<key>[^[]*)\[(?P<field>.*)\]', key) if m and m.group('key') == 'md5': md5[m.group('field')] = value error_msg = None if self.do_md5_check: if not upload_id or not md5: error_msg = "Both 'upload_id' and 'md5' are required" elif not upload_id: error_msg = "'upload_id' is required" if error_msg: raise ChunkedUploadError(status=http_status.HTTP_400_BAD_REQUEST, detail=error_msg) for chunked_upload in self.get_queryset(request).filter(dataset__upload_id=upload_id): self.validate(request) self.is_valid_chunked_upload(chunked_upload) if self.do_md5_check: self.md5_check(chunked_upload, md5[chunked_upload.field_name]) chunked_upload.status = COMPLETE chunked_upload.completed_on = timezone.now() self._save(chunked_upload) mutable = data._mutable data._mutable = True data['file_name'] = chunked_upload.field_name data._mutable = mutable self.on_completion(chunked_upload.get_uploaded_file(), request) return Response(self.get_response_data(upload_id, request), status=http_status.HTTP_200_OK)
def dict_querydict(dict_): """ Converts a value created by querydict_dict back into a Django QueryDict value. """ q = QueryDict("", mutable=True) for k, v in dict_.iteritems(): q.setlist(k, v) q._mutable = False return q
def test_add_wildcard_without_exact_match(self): query_dict = QueryDict('', mutable=True) query_dict.update(**{'q': 'some search phrase', 'exact_match': False}) query_dict._mutable = False request = FakeRequest(query_dict) SearchStringFormatter.add_wildcard(request) self.assertEquals(request.GET['q'], 'some* search* phrase*')
def test_add_wildcard_without_query_string(self): query_dict = QueryDict('', mutable=True) query_dict.update(**{'exact_match': False}) query_dict._mutable = False request = FakeRequest(query_dict) SearchStringFormatter.add_wildcard(request) self.assertTrue('q' not in request.GET)
def to_querydict(dict): """ Converts a value created by querydict_dict back into a Django QueryDict value. """ q = QueryDict("", mutable=True) for k, v in dict.items(): q.setlist(k, v) q._mutable = False return q
def test_add_wildcard_with_empty_query_string(self): query_dict = QueryDict('', mutable=True) query_dict.update(**{'q': '', 'exact_match': False}) query_dict._mutable = False request = FakeRequest(query_dict) SearchStringFormatter.add_wildcard(request) self.assertEquals(request.GET['q'], '')
def get_add_url(self): url = 'stark:%s_%s_add' % (self.model._meta.app_label, self.model._meta.model_name) add_url = reverse(url, ) # print("edit_url",edit_url) q = QueryDict() q._mutable = True q["_listfilter"] = self.request.GET.urlencode() new_edit_url = add_url + "?%s" % q.urlencode() return new_edit_url
def get_edit_link_tag(self, obj, val): edit_url = self.model_stark_obj.get_edit_url(obj) q = QueryDict() q._mutable = True if not self.request.GET: q["_page"] = 1 else: q["_listfilter"] = self.request.GET.urlencode() new_edit_url = edit_url + "?%s" % q.urlencode() return mark_safe("<a href='" + new_edit_url + "'>" + val + "</a>")
def json_decode(body, encoding=None): data = json.loads(body, encoding=encoding) query_dict = QueryDict(mutable=True) try: query_dict.update(data) except AttributeError: # data is not a mapping (hasn't items() method) raise ValueError query_dict._mutable = False return query_dict
def build_querydict(data): qd = QueryDict('', mutable=True) for key, value in data.items(): if isinstance(value, list): for v in value: qd.update({key: v}) else: qd.update({key: value}) qd._mutable = False return qd
def get_query_params(self): """ 获取query_params,相当于url后面的拼接参数 """ qd = QueryDict() qd._mutable = True url = self.request.get_full_path() qd['next'] = url query_params = qd.urlencode() return query_params
def get_query_params(self): url = self.request.get_full_path() # 新建QueryDict()对象 qd = QueryDict() # 添加修改权限 qd._mutable = True # 增加一堆键值对 qd['next'] = url query_params = qd.urlencode() return query_params
def get_next(self): # 获取当前页面的全路径, 包含get参数, 如: /crm/customer_list/?query=user&page=2 next_url = self.request.get_full_path() # 创建QueryDict字典 qDict = QueryDict() # 将这个字典设为可修改 qDict._mutable = True qDict['next'] = next_url return qDict
def get_add_btn(self): # 获取添加按钮 url = self.request.get_full_path() qd = QueryDict() qd._mutable = True qd['next'] = url query_params = qd.urlencode() add_btn = '<a href="{}?{}" class="btn btn-primary btn-sm" style="margin-bottom: 10px">添加</a>'.format( reverse('crm:add_customer', args=(0, )), query_params) return mark_safe(add_btn), query_params
def get_add_btn(self): """ 获取add按钮 """ qd = QueryDict() qd._mutable = True url = self.request.get_full_path() qd['next'] = url query_params = qd.urlencode() add_btn = '<a href="{}?{}" class="btn btn-info" style="margin: 11px 0">添加客户</a>'.format( reverse('crm:add_customer'), query_params) return add_btn, query_params
def dict_to_querydict(dict_): """ Converts a dict value into the Django's QueryDict object. """ query_dict = QueryDict('', mutable=True) for name, value in dict_.items(): if isinstance(name, list): query_dict.setlist(name, value) else: query_dict.appendlist(name, value) query_dict._mutable = False return query_dict
def parse(query_params, request): if get_style(request) == 'camelcase': q = QueryDict('', mutable=True, encoding=query_params.encoding) for k, l in query_params.lists(): q.setlist( to_snake_case(k), k != ORDERING_PARAM and l or list(map(to_snake_case, l))) q._mutable = False return q else: return query_params
def cleaned_data_querydict(self): """ Creates an immutable QueryDict instance from the form's cleaned_data """ query = QueryDict("", mutable=True) # make sure cleaned_data is available, if possible ... self.is_valid() cleaned_data = getattr(self, "cleaned_data", {}) for key, values in cleaned_data.items(): query.setlist(key=key, list_=values) query._mutable = False return query
def cleaned_data_querydict(self): """ Creates an immutable QueryDict instance from the form's cleaned_data """ query = QueryDict('', mutable=True) # make sure cleaned_data is available, if possible ... self.is_valid() cleaned_data = getattr(self, 'cleaned_data', {}) for key, values in cleaned_data.items(): query.setlist(key=key, list_=values) query._mutable = False return query
def json_decode(body, encoding=None): data = json.loads(body, encoding=encoding) query_dict = QueryDict(mutable=True) try: query_dict.update(data) except AttributeError: raise ValueError query_dict._mutable = False return query_dict
def modify(self, obj=None, is_head=False): if obj: edit_url = self.get_edit_url(obj) q = QueryDict() q._mutable = True if not self.request.GET: q[self.page_key] = 1 else: q["_listfilter"] = self.request.GET.urlencode() new_edit_url = edit_url + "?%s" % q.urlencode() return mark_safe("<a href='" + new_edit_url + "'>编辑</a>") if is_head: return "操作"
def get_add_btn(self): url = self.request.get_full_path() # 新建QueryDict()对象 qd = QueryDict() # 添加修改权限 qd._mutable = True # 增加一堆键值对 qd['next'] = url # 将QueryDict对象转化成a=b的形式 query_params = qd.urlencode() # 生成一个新建标签,并拼接url add_btn = '<a class="btn btn-primary" href="{}?{} ">增加</a>'.format( reverse('add_customer'), query_params) return add_btn, query_params
def params_to_snake_case(request: HttpRequest, method: str): """ Convert GET or POST params to snake_case :param request: :param method: :return: """ request_method = getattr(request, method) request_method._mutable = True request_params_dict = nested_snake_case_transformer(request_method.dict()) request_params = QueryDict('', mutable=True) request_params.update(request_params_dict) request_params._mutable = False setattr(request, method, request_params)
def get_add_btn(self): # 获取添加按钮 url = self.request.get_full_path() qd = QueryDict() qd._mutable = True qd['next'] = url # next=%2Fcrm%2Fcustomer_list%2F%3Fquery%3Dalex%26page%3D2 query_params = qd.urlencode() # add_btn = '<a href="{}?next={}" class="btn btn-primary btn-sm">添加</a>'.format(reverse('add_customer'), url) add_btn = '<a href="{}?{}" class="btn btn-primary btn-sm">添加</a>'.format(reverse('add_customer'), query_params) return mark_safe(add_btn), query_params
def get_add_btn(self): # 获取添加按钮 url = self.request.get_full_path() qd = QueryDict() qd._mutable = True qd['next'] = url print(qd) query_params = qd.urlencode() print('query_params', query_params) # add_btn = '<a href="{}?next={}" class="btn btn-primary btn-sm" style="margin-bottom: 10px">添加</a>'.format( # reverse('crm:add_customer'), url) # 这是一种给templates加next 的方法,编辑那也是一种直接将next={{ query_params }} add_btn1 = '<a href="{}?{}" class="btn btn-primary btn-sm" style="margin-bottom: 10px">添加</a>'.format( reverse('crm:add_customer'), query_params) # print(add_btn) print(add_btn1) return mark_safe(add_btn1), query_params
def modify(self, obj=None, is_head=False): if obj: edit_url = self.get_edit_url(obj) # current_page = self.get_page_obj(request).current_page # edit_url=edit_url+"?page=%s"%current_page # edit_url=request.get_full_path() q = QueryDict() q._mutable = True if not self.request.GET: q["_page"] = 1 else: q["_listfilter"] = self.request.GET.urlencode() new_edit_url = edit_url + "?%s" % q.urlencode() # print(new_edit_url) return mark_safe("<a href='" + new_edit_url + "'>编辑</a>") if is_head: return "操作"
def set_profile(request): post_data = request.POST.copy() profile = get_profile(request) # print('profile admin', profile.sex) # print('post_data', post_data) new_dict = dict(post_data.iterlists()) # print('new_dict', new_dict) new_dict[u"sex"] = [unicode(profile.sex)] # print('new_dict_sex', new_dict) # convertir el dict {} python en un QueryDict post_data = QueryDict("", mutable=True) for k, v in new_dict.iteritems(): post_data.setlist(k, v) post_data._mutable = False print('post_data2', post_data) profile_form = UserProfileForm(None, post_data, instance=profile) if profile_form.is_valid(): print('tamos entrando') # print(profile_form.se) profile_form.save() else: print('errors', profile_form.errors)
def test_accounts_login(client, request_users, settings): user = request_users["user"] if user.username == "nobody": return settings.POOTLE_CAPTCHA_ENABLED = False password = request_users["password"] qdict = QueryDict(mutable=True) qdict.update( {'login': user.username, 'password': password}) qdict._mutable = False response = client.post( '/accounts/login/', qdict, HTTP_X_REQUESTED_WITH='XMLHttpRequest') email = EmailAddress.objects.filter(user=user, primary=True).first() assert response.request['PATH_INFO'] == '/accounts/login/' assert response.status_code == 200 if email is not None and email.verified: assert response.json() == {u"location": "/"} else: assert response.json() == {u"location": "/accounts/confirm-email/"}
def test_submit_with_suggestion_and_comment(client, request_users, settings, system): """Tests translation can be applied after suggestion is accepted.""" settings.POOTLE_CAPTCHA_ENABLED = False Comment = get_comment_model() unit = Unit.objects.filter( suggestion__state__name='pending', state=UNTRANSLATED)[0] last_sub_pk = unit.submission_set.order_by( "id").values_list("id", flat=True).last() or 0 sugg = Suggestion.objects.filter(unit=unit, state__name='pending')[0] user = request_users["user"] if user.username != "nobody": client.login( username=user.username, password=request_users["password"]) url = '/xhr/units/%d/' % unit.id edited_target = "Edited %s" % sugg.target_f comment = 'This is a comment!' qdict = QueryDict(mutable=True) qdict.update( {'state': False, 'target_f_0': edited_target, 'suggestion': sugg.id, 'comment': comment}) qdict._mutable = False response = client.post( url, qdict, HTTP_X_REQUESTED_WITH='XMLHttpRequest') suggestion = Suggestion.objects.get(id=sugg.id) unit = Unit.objects.get(id=unit.id) new_subs = unit.submission_set.filter(id__gt=last_sub_pk).order_by("id") if check_permission('translate', response.wsgi_request): assert response.status_code == 200 content = json.loads(response.content) assert content['newtargets'] == [edited_target] assert content['user_score'] == response.wsgi_request.user.public_score assert content['checks'] is None unit_source = unit.unit_source.get() assert unit_source.created_by == system assert unit_source.created_with == SubmissionTypes.SYSTEM assert unit.change.submitted_by == suggestion.user assert unit.change.reviewed_by == user assert unit.change.changed_with == SubmissionTypes.WEB assert suggestion.state.name == 'accepted' assert str(unit.target) == edited_target assert (Comment.objects .for_model(suggestion) .get().comment == comment) assert new_subs.count() == 2 target_sub = new_subs[0] assert target_sub.old_value == "" assert target_sub.new_value == unit.target assert target_sub.field == SubmissionFields.TARGET assert target_sub.type == SubmissionTypes.WEB assert target_sub.submitter == unit.change.submitted_by assert target_sub.suggestion == suggestion assert target_sub.revision == unit.revision assert target_sub.creation_time == unit.change.reviewed_on state_sub = new_subs[1] assert state_sub.old_value == str(UNTRANSLATED) assert state_sub.new_value == str(unit.state) assert state_sub.suggestion == suggestion assert state_sub.field == SubmissionFields.STATE assert state_sub.type == SubmissionTypes.WEB assert state_sub.submitter == unit.change.submitted_by assert state_sub.revision == unit.revision assert state_sub.creation_time == unit.change.reviewed_on else: assert response.status_code == 403 assert suggestion.state.name == "pending" assert unit.target == "" assert new_subs.count() == 0 with pytest.raises(UnitChange.DoesNotExist): unit.change