def save(self, force_insert=False, force_update=False, using=None, update_fields=None): import decimal super(OfferSheet, self).save(force_insert, force_update, using, update_fields) if self.discount_amount > 0: sql = ( "UPDATE sale_offeritem a SET a.discount_price = a.sale_price - " "((SELECT discount_amount/amount FROM sale_offersheet WHERE id = %s) * (a.sale_price*a.cnt)/a.cnt) WHERE a.master_id = %s" ) params = [self.id, self.id] # print(sql % (self.id,self.id)) generic.update(sql, params) item_count = OfferItem.objects.filter(master=self).count() if self.attach and item_count == 0: path = os.path.join(settings.MEDIA_ROOT, self.attach.name) workbook = xlrd.open_workbook(path) sheet = workbook.sheet_by_index(0) row_count = sheet.nrows with transaction.atomic(): total_amount = decimal.Decimal(0) for row_index in range(row_count): row = sheet.row_values(row_index) if row_index == 0: doc_type = row[1] if doc_type.startswith("0"): break else: continue elif row_index < 3: continue material = None measure = None try: measure = Measure.objects.get(code=row[4]) except Exception as e: measure = Measure.objects.create(code=row[4], name=force_text(row[5])) try: material = Material.objects.get(code=row[0]) except Exception as e: material = Material(code=row[0], name=force_text(row[1]), spec=force_text(row[2])) material.sale_price = row[6] material.purchase_price = row[7] material.save() OfferItem.objects.create( master=self, material=material, measure=measure, cnt=row[8], brand=force_text(row[3]), cost_price=row[7], sale_price=row[6], ) total_amount += decimal.Decimal(row[6]) * decimal.Decimal(row[8]) sql = "update sale_offersheet set amount = %s where id=%s" params = [total_amount, self.id] generic.update(sql, params)
def fill_categories_sheet(self): row_number = 1 self.worksheets['categories'].write_row( row_number, 0, ( '№', force_text(_('Category')), force_text(_('Count\n utilities')), ), self.formats['header'] ) self.worksheets['categories'].set_row(1, 30) categories = Category.objects.categories_with_count_utilities().iterator() for i, obj in enumerate(categories, 1): row_number += 1 self.worksheets['categories'].write(row_number, 0, i, self.formats['center']) self.worksheets['categories'].write(row_number, 1, force_text(obj)) self.worksheets['categories'].write(row_number, 2, obj.count_utilities, self.formats['center']) self.worksheets['categories'].set_column('A:A', 5) self.worksheets['categories'].set_column('B:B', 100) self.worksheets['categories'].set_column('C:C', 10)
def test_api_authentication(admin_user): shop = factories.get_default_shop() authentication = APITokenAuthentication() factory = APIRequestFactory() def get_request(jwt, shop): request = factory.get('/api/shuup/shop/') request.META["HTTP_AUTHORIZATION"] = "JWT %s" % jwt request.shop = shop return request # no API Key jwt = jwt_encode_handler({}) request = get_request(jwt, shop) assert authentication.authenticate(request) is None # invalid username jwt = jwt_encode_handler({"username": "******"}) request = get_request(jwt, shop) with pytest.raises(AuthenticationFailed): authentication.authenticate(request) # correct username jwt = jwt_encode_handler({"username": admin_user.username}) request = get_request(jwt, shop) user, token = authentication.authenticate(request) assert user == admin_user assert force_text(token) == force_text(jwt) # user is not active admin_user.is_active = False admin_user.save() with pytest.raises(AuthenticationFailed): authentication.authenticate(request)
def get(self, request, *args, **kwargs): if request.method == 'GET': guid = request.GET.get('guid', None) if guid is None: return self.render_to_response(self._results_to_context(('missing guid', False, [], ))) if not guid: return self.render_to_response(self._results_to_context((NO_ERR_RESP, False, [], ))) else: return self.render_to_response(self._results_to_context(('not a get request', False, [], ))) try: address = AddrObj.objects.get(pk=guid) except AddrObj.DoesNotExist: return self.render_to_response(self._results_to_context(('wrong guid', False, [], ))) city = self._get_city_obj(address) if city is None: return self.render_to_response(self._results_to_context((NO_ERR_RESP, False, [], ))) areas = AddrObj.objects.filter(parentguid=city.pk, shortname='р-н') if areas: return self.render_to_response(self._results_to_context(( NO_ERR_RESP, False, ((force_text(a.pk), force_text(a)) for a in areas), )) ) return self.render_to_response(self._results_to_context((NO_ERR_RESP, False, [], )))
def save(self, force_insert=False, force_update=False, using=None, update_fields=None): super(InitialInventory, self).save(force_insert, force_update, using, update_fields) count = InitItem.objects.filter(master=self).count() if self.attach and count == 0: path = os.path.join(settings.MEDIA_ROOT, self.attach.name) reader = csv.reader(open(path, 'r')) index = 0 with transaction.atomic(): for code, name, description, unit_code, unit_name, warehouse_code, warehouse_name, price, cnt in reader: index += 1 if index == 1: continue material = None measure = None house = None try: measure = Measure.objects.get(code=unit_code) except Exception as e: measure = Measure.objects.create( code=unit_code, name=force_text(unit_name.decode('gbk'))) try: house = Warehouse.objects.get(code=warehouse_code) except Exception as e: house = Warehouse.objects.create( code=warehouse_code, name=force_text(warehouse_name.decode('gbk'))) try: material = Material.objects.get(code=code) except Exception as e: material = Material( code=code, name=force_text(name.decode('gbk')), spec=force_text(description.decode('gbk')), warehouse=house) material.stock_price = price material.save() InitItem.objects.create(master=self, material=material, price=price, cnt=cnt, warehouse=house, measure=measure, source=self.code)
def export_selected_data(self, request, queryset): ops = self.model._meta workbook = xlwt.Workbook(encoding='utf-8') dd = datetime.date.today().strftime('%Y%m%d') file_name = force_text(ops.verbose_name + dd) sheet = workbook.add_sheet(force_text(ops.verbose_name)) obj_fields = getattr(self, 'export_fields', None) or self.list_display or self.fields head_col_index = 0 for field in obj_fields: col_name = field try: f = ops.get_field(field) col_name = f.verbose_name except Exception as e: f = getattr(self.model, field) if hasattr(f, 'short_description'): col_name = f.short_description sheet.write(0, head_col_index, force_text(col_name)) head_col_index += 1 row_index = 1 for obj in queryset: col_index = 0 for field in obj_fields: f = field try: f = ops.get_field(field) except Exception as e: pass v = getattr(obj, field, '') if hasattr(v, '__call__') or callable(v): v = v() elif type(f) == fields.DateField: v = v.strftime('%Y-%m-%d') elif type(f) == fields.DateTimeField: v = v.strftime('%Y-%m-%d %H:%M') elif type(f) == fields.CharField and f.choices: fc = 'get_' + field + '_display' v = getattr(obj, fc)() elif type(f) == related.ForeignKey: v = str(v) sheet.write(row_index, col_index, v) col_index += 1 row_index += 1 response = HttpResponse(content_type='application/vnd.ms-excel') agent = request.META.get('HTTP_USER_AGENT') nn = smart_str(file_name) if agent and re.search('MSIE', agent): nn = urlquote(file_name) response['Content-Disposition'] = 'attachment; filename=%s.xls' % nn workbook.save(response) return response
def save(self, force_insert=False, force_update=False, using=None, update_fields=None): super(WorkOrder, self).save(force_insert, force_update, using, update_fields) if self.service: material = self.service if self.woextravalue_set.count( ) < 1 and material.extraparam_set and material.extraparam_set.count( ) > 0: for param in material.extraparam_set.all(): extra_param = WOExtraValue.objects.create(workorder=self, param_name=param) self.woextravalue_set.add(extra_param) item_count = WOItem.objects.filter(workorder=self).count() if self.detail and item_count == 0: path = os.path.join(settings.MEDIA_ROOT, self.detail.name) workbook = xlrd.open_workbook(path) sheet = workbook.sheet_by_index(0) row_count = sheet.nrows with transaction.atomic(): for row_index in range(row_count): row = sheet.row_values(row_index) if row_index == 0: doc_type = row[1] if doc_type.startswith('0'): break else: continue elif row_index < 3: continue material = None measure = None try: measure = Measure.objects.get(code=row[4]) except Exception as e: measure = Measure.objects.create(code=row[4], name=force_text( row[5])) try: material = Material.objects.get(code=row[0]) except Exception as e: material = Material(code=row[0], name=force_text(row[1]), spec=force_text(row[2])) material.save() WOItem.objects.create(workorder=self, material=material, measure=measure, amount=row[6])
def export_selected_data(self,request,queryset): ops = self.model._meta workbook = xlwt.Workbook(encoding='utf-8') dd = datetime.date.today().strftime('%Y%m%d') file_name = force_text(ops.verbose_name+dd) sheet = workbook.add_sheet(force_text(ops.verbose_name)) obj_fields = getattr(self,'export_fields',None) or self.list_display or self.fields head_col_index = 0 for field in obj_fields: col_name = field try: f = ops.get_field(field) col_name = f.verbose_name except Exception as e: f = getattr(self.model,field) if hasattr(f,'short_description'): col_name = f.short_description sheet.write(0,head_col_index,force_text(col_name)) head_col_index+=1 row_index = 1 for obj in queryset: col_index = 0 for field in obj_fields: f = field try: f = ops.get_field(field) except Exception as e: pass v = getattr(obj,field,'') if hasattr(v,'__call__') or callable(v): v = v() elif type(f) == fields.DateField: v = v.strftime('%Y-%m-%d') elif type(f) == fields.DateTimeField: v = v.strftime('%Y-%m-%d %H:%M') elif type(f) == fields.CharField and f.choices: fc = 'get_'+field+'_display' v = getattr(obj,fc)() elif type(f) == related.ForeignKey: v = str(v) sheet.write(row_index,col_index,v) col_index += 1 row_index += 1 response = HttpResponse(content_type='application/vnd.ms-excel') agent = request.META.get('HTTP_USER_AGENT') nn = smart_str(file_name) if agent and re.search('MSIE',agent): nn = urlquote(file_name) response['Content-Disposition'] = 'attachment; filename=%s.xls'%nn workbook.save(response) return response
def test_edit_shared_file(admin_user): with override_settings(SHUUP_ENABLE_MULTIPLE_SHOPS=True): shop1 = factories.get_shop(identifier="shop1", enabled=True) shop2 = factories.get_shop(identifier="shop2", enabled=True) folder1 = Folder.objects.create(name="folder1") folder2 = Folder.objects.create(name="folder2") file = File.objects.create(original_filename="test.jpg", folder=folder1) # Shared file file_count = File.objects.count() assert force_text(file) == "test.jpg" response = _mbv_command(shop1, admin_user, {"action": "rename_file", "id": file.pk, "name": "test.tiff"}) assert not response["success"] response = _mbv_command(shop1, admin_user, {"action": "move_file", "file_id": file.pk, "folder_id": folder2.pk}) assert not response["success"] assert File.objects.get(pk=file.pk).folder == folder1 response = _mbv_command(shop1, admin_user, {"action": "delete_file", "id": file.pk}) assert not response["success"] # Let's make sure rename works when only one shop owns the file media_file = MediaFile.objects.create(file=file) media_file.shops.add(shop1) response = _mbv_command(shop1, admin_user, {"action": "rename_file", "id": file.pk, "name": "test.tiff"}) assert response["success"] file = File.objects.get(pk=file.pk) assert force_text(file) == "test.tiff" # Let's move the file to different folder response = _mbv_command(shop1, admin_user, {"action": "move_file", "file_id": file.pk, "folder_id": folder2.pk}) assert response["success"] assert File.objects.get(pk=file.pk).folder == folder2 # Then add second shop for the file and let's check and # renaming should be disabled again. media_file.shops.add(shop2) response = _mbv_command(shop1, admin_user, {"action": "rename_file", "id": file.pk, "name": "test.tiff"}) assert not response["success"] response = _mbv_command(shop1, admin_user, {"action": "delete_file", "id": file.pk}) assert not response["success"] response = _mbv_command(shop2, admin_user, {"action": "rename_file", "id": file.pk, "name": "test.tiff"}) assert not response["success"] response = _mbv_command(shop2, admin_user, {"action": "delete_file", "id": file.pk}) assert not response["success"] # Finally remove the file as shop2 media_file.shops.remove(shop1) response = _mbv_command(shop1, admin_user, {"action": "delete_file", "id": file.pk}) assert response["error"] == "File matching query does not exist." response = _mbv_command(shop2, admin_user, {"action": "delete_file", "id": file.pk}) assert response["success"] assert File.objects.count() == file_count - 1
def save(self, force_insert=False, force_update=False, using=None, update_fields=None): import decimal super(OfferSheet,self).save(force_insert,force_update,using,update_fields) if self.discount_amount > 0: sql = 'UPDATE sale_offeritem a SET a.discount_price = a.sale_price - ' \ '((SELECT discount_amount/amount FROM sale_offersheet WHERE id = %s) * (a.sale_price*a.cnt)/a.cnt) WHERE a.master_id = %s' params = [self.id,self.id] # print sql % (self.id,self.id) generic.update(sql,params) item_count = OfferItem.objects.filter(master=self).count() if self.attach and item_count == 0: path = os.path.join(settings.MEDIA_ROOT,self.attach.name) workbook = xlrd.open_workbook(path) sheet = workbook.sheet_by_index(0) row_count = sheet.nrows with transaction.atomic(): total_amount = decimal.Decimal(0) for row_index in range(row_count): row = sheet.row_values(row_index) if row_index == 0: doc_type = row[1] if doc_type.startswith('0'): break else: continue elif row_index < 3: continue material = None measure = None try: measure = Measure.objects.get(code=row[4]) except Exception as e: measure = Measure.objects.create(code=row[4],name=force_text(row[5])) try: material = Material.objects.get(code=row[0]) except Exception as e: material = Material(code=row[0],name=force_text(row[1]),spec=force_text(row[2])) material.sale_price = row[6] material.purchase_price = row[7] material.save() OfferItem.objects.create(master=self,material=material,measure=measure,cnt=row[8],brand=force_text(row[3]), cost_price=row[7],sale_price=row[6]) total_amount += decimal.Decimal(row[6])*decimal.Decimal(row[8]) sql = 'update sale_offersheet set amount = %s where id=%s' params = [total_amount,self.id] generic.update(sql,params)
def test_edit_shared_file(admin_user): with override_settings(E-Commerce_ENABLE_MULTIPLE_SHOPS=True): shop1 = factories.get_shop(identifier="shop1", enabled=True) shop2 = factories.get_shop(identifier="shop2", enabled=True) folder1 = Folder.objects.create(name="folder1") folder2 = Folder.objects.create(name="folder2") file = File.objects.create(original_filename="test.jpg", folder=folder1) # Shared file file_count = File.objects.count() assert force_text(file) == "test.jpg" response = _mbv_command(shop1, admin_user, {"action": "rename_file", "id": file.pk, "name": "test.tiff"}) assert not response["success"] response = _mbv_command(shop1, admin_user, {"action": "move_file", "file_id": file.pk, "folder_id": folder2.pk}) assert not response["success"] assert File.objects.get(pk=file.pk).folder == folder1 response = _mbv_command(shop1, admin_user, {"action": "delete_file", "id": file.pk}) assert not response["success"] # Let's make sure rename works when only one shop owns the file media_file = MediaFile.objects.create(file=file) media_file.shops.add(shop1) response = _mbv_command(shop1, admin_user, {"action": "rename_file", "id": file.pk, "name": "test.tiff"}) assert response["success"] file = File.objects.get(pk=file.pk) assert force_text(file) == "test.tiff" # Let's move the file to different folder response = _mbv_command(shop1, admin_user, {"action": "move_file", "file_id": file.pk, "folder_id": folder2.pk}) assert response["success"] assert File.objects.get(pk=file.pk).folder == folder2 # Then add second shop for the file and let's check and # renaming should be disabled again. media_file.shops.add(shop2) response = _mbv_command(shop1, admin_user, {"action": "rename_file", "id": file.pk, "name": "test.tiff"}) assert not response["success"] response = _mbv_command(shop1, admin_user, {"action": "delete_file", "id": file.pk}) assert not response["success"] response = _mbv_command(shop2, admin_user, {"action": "rename_file", "id": file.pk, "name": "test.tiff"}) assert not response["success"] response = _mbv_command(shop2, admin_user, {"action": "delete_file", "id": file.pk}) assert not response["success"] # Finally remove the file as shop2 media_file.shops.remove(shop1) response = _mbv_command(shop1, admin_user, {"action": "delete_file", "id": file.pk}) assert response["error"] == "File matching query does not exist." response = _mbv_command(shop2, admin_user, {"action": "delete_file", "id": file.pk}) assert response["success"] assert File.objects.count() == file_count - 1
def save(self, force_insert=False, force_update=False, using=None, update_fields=None): super(InitialInventory, self).save(force_insert, force_update, using, update_fields) count = InitItem.objects.filter(master=self).count() if self.attach and count == 0: path = os.path.join(settings.MEDIA_ROOT, self.attach.name) reader = csv.reader(open(path, "r")) index = 0 with transaction.atomic(): for code, name, description, unit_code, unit_name, warehouse_code, warehouse_name, price, cnt in reader: index += 1 if index == 1: continue material = None measure = None house = None try: measure = Measure.objects.get(code=unit_code) except Exception as e: measure = Measure.objects.create(code=unit_code, name=force_text(unit_name.decode("gbk"))) try: house = Warehouse.objects.get(code=warehouse_code) except Exception as e: house = Warehouse.objects.create( code=warehouse_code, name=force_text(warehouse_name.decode("gbk")) ) try: material = Material.objects.get(code=code) except Exception as e: material = Material( code=code, name=force_text(name.decode("gbk")), spec=force_text(description.decode("gbk")), warehouse=house, ) material.stock_price = price material.save() InitItem.objects.create( master=self, material=material, price=price, cnt=cnt, warehouse=house, measure=measure, source=self.code, )
def adapt(text): # make sure connection is open connection.cursor() connection.connection.set_client_encoding('UNICODE') text = text print type(force_text(text)) # use Unicode psycopg2.extensions.register_type(psycopg2.extensions.UNICODE, connection.connection) psycopg2.extensions.register_type(psycopg2.extensions.UNICODEARRAY, connection.connection) a = psycopg2.extensions.adapt(force_text(text)) a.prepare(connection.connection) return unicode(a.getquoted(), 'utf-8')
def __init__(self, *args, **kwargs): kwargs.setdefault('max_length', 125) available_themes = list(get_available_themes()) choices = kwargs.get('choices', None) if choices is None: kwargs['choices'] = zip(available_themes, available_themes) else: diff = (set(force_text(t[0]) for t in choices) - set(available_themes)) if diff: raise ImproperlyConfigured( 'VestField got unknow themes: {}'.format(force_text(diff))) super(VestField, self).__init__(*args, **kwargs)
def save(self, force_insert=False, force_update=False, using=None, update_fields=None): super(PurchaseOrder,self).save(force_insert,force_update,using,update_fields) if self.discount_amount > 0: sql = 'UPDATE purchase_poitem a SET a.discount_price = ' \ 'a.price-((SELECT discount_amount/amount FROM purchase_purchaseorder WHERE id=%s)*a.amount/a.cnt) WHERE a.po_id = %s' params = [self.id,self.id] generic.update(sql,params) item_count = POItem.objects.filter(po=self).count() if self.attach and item_count == 0: path = os.path.join(settings.MEDIA_ROOT,self.attach.name) workbook = xlrd.open_workbook(path) sheet = workbook.sheet_by_index(0) row_count = sheet.nrows with transaction.atomic(): total_amount = decimal.Decimal(0) for row_index in range(row_count): row = sheet.row_values(row_index) if row_index == 0: doc_type = row[1] if doc_type.startswith('0'): break else: continue elif row_index < 3: continue material = None measure = None try: measure = Measure.objects.get(code=row[4]) except Exception,e: measure = Measure.objects.create(code=row[4],name=force_text(row[5])) try: material = Material.objects.get(code=row[0]) except Exception,e: material = Material(code=row[0],name=force_text(row[1]),spec=force_text(row[2])) material.purchase_price = row[6] material.save() amount = decimal.Decimal(row[6])*decimal.Decimal(row[7]) POItem.objects.create(po=self,material=material,measure=measure,cnt=row[7],price=row[6],amount=amount) total_amount += amount sql = 'update purchase_purchaseorder set amount = %s where id=%s' params = [total_amount,self.id] generic.update(sql,params)
def fill_summary_sheet(self): worksheet = self.worksheets['summary'] row_num = 2 categories = Category.objects.prefetch_related('utilities').iterator() for category in categories: self.worksheets['summary'].merge_range( row_num, 0, row_num, 2, force_text(category), self.formats['category_title'] ) self.worksheets['summary'].set_row(row_num, 30) if category.utilities.exists(): utilities = category.utilities.utilities_with_rating() utilities = utilities.annotate(_temp=IsNullAsLast('rating')) utilities = utilities.order_by('_temp', '-rating') utilities = utilities.iterator() for i, utility in enumerate(utilities, start=1): row_num += 1 worksheet.write(row_num, 0, i, self.formats['center']) utility_display_text = force_text(utility) worksheet.write(row_num, 1, utility_display_text, self.formats['object_display_text']) rating = self.empty_value_display if utility.rating is None else utility.rating worksheet.write(row_num, 2, rating, self.formats['center']) worksheet.set_row(row_num, self.determinate_height_of_row(utility_display_text)) else: row_num += 1 worksheet.merge_range( row_num, 0, row_num, 2, force_text(_('Category has not utilities')), self.formats['none_utilities'] ) row_num += 2 worksheet.set_column(0, 0, 5) worksheet.set_column(1, 1, 50) worksheet.set_column(2, 2, 10)
def safe_json_load(request): """Verify the request and return the deserialized request body.""" signature = request.META.get("HTTP_X_HUB_SIGNATURE") expected = compute_signature(request.body, force_bytes(GITHUB_KEY)) if not constant_time_compare(signature, expected): raise InvalidSignature return json.loads(force_text(request.body))
def get(self, request, **kwargs): obj = self.get_object() collector = Collector(using='default') collector.collect([obj]) collector.sort() ret = {'items': []} for model, instances in collector.data.items(): display_obj = rel_model.get(model._meta.model_name, lambda original, related: related) instances = [display_obj(obj, instance) for instance in instances] instances = filter( lambda instance: hasattr(instance, 'get_absolute_url'), instances) counter = Counter(instances) ret['items'] += [{ 'name': force_text(instance), 'preview_url': request._request.build_absolute_uri( instance.get_absolute_url()), 'type': model._meta.verbose_name, 'count': count } for instance, count in counter.items()] ret['items'].sort( key=lambda item: item['type'] != obj._meta.verbose_name) return Response(ret)
def get_version_name(self): name = "{root}_{options}{extension}".format( root=force_text(self.file_object.filename_root), options=self.options_as_string, extension=self.file_object.extension, ) return name
def __init__(self, **kwargs): super(ShopBaseForm, self).__init__(**kwargs) self.fields["currency"] = forms.ChoiceField( choices=get_currency_choices(), required=True, label=_("Currency"), help_text= _("The primary shop currency. This is the currency used when selling your products." )) staff_members = Select2MultipleField( label=_("Staff"), help_text=_("Select staff members for this shop."), model=get_user_model(), required=False) staff_members.widget = QuickAddUserMultiSelect( attrs={"data-model": "auth.User"}) initial_members = (self.instance.staff_members.all() if self.instance.pk else []) staff_members.widget.choices = [(member.pk, force_text(member)) for member in initial_members] self.fields["staff_members"] = staff_members self.fields["domain"].required = ShuupSettings.get_setting( "SHUUP_ENABLE_MULTIPLE_SHOPS") self.disable_protected_fields()
def adapt(text): a = psycopg2.extensions.adapt(force_text(text)) if connection.connection is None: # re-initialize connection connection.cursor().close() a.prepare(connection.connection) return a
def _find_related_values(self, field_name, sess, value): is_related_field = False if not value: return (value, is_related_field) field_mapping = sess.importer.mapping.get(field_name) for related_field, relmapper in sess.importer.relation_map_cache.items(): if related_field.name != field_name: continue is_related_field = True if isinstance(related_field, ForeignKey): try: value = int(value) # this is because xlrd causes 1 to be 1.0 except: pass value = relmapper.fk_cache.get(str(value)) break else: value = sess.importer.relation_map_cache.get(field_mapping.get("field")).map_cache[value] break if field_mapping.get("is_enum_field"): field = field_mapping.get("field") for k, v in field.get_choices(): if fold_mapping_name(force_text(v)) == fold_mapping_name(value): value = k break return (value, is_related_field)
def adapt(text): # make sure the connection is open connection.cursor() a = psycopg2.extensions.adapt(force_text(text)) a.prepare(connection.connection) return a
def post(self, request, *args, **kwargs): shop = request.shop cookie_categories = list(GDPRCookieCategory.objects.filter(shop=shop, always_active=True)) for field, value in request.POST.items(): field_match = re.match(COOKIE_CONSENT_RE, field) if field_match and value.lower() in ["on", "1"]: cookie_category = GDPRCookieCategory.objects.filter(shop=shop, id=field_match.groups()[0]).first() if cookie_category: cookie_categories.append(cookie_category) consent_documents = [] if has_installed("shuup.simple_cms"): consent_documents = get_active_consent_pages(shop) cookie_data = get_cookie_consent_data(cookie_categories, consent_documents) if request.META.get("HTTP_REFERER"): redirect_url = request.META["HTTP_REFERER"] else: redirect_url = force_text(reverse("shuup:index")) response = HttpResponseRedirect(redirect_url) add_consent_to_response_cookie(response, cookie_data) return response
def conv_choice(choice): """Helper to convert choices dict to comparable value. """ return ( choice['query_string'], force_text(choice['display']), choice['selected'], )
def _iter_translations(value): for code, locale in [('zh', 'zh-hant'), ('en', 'en-us')]: with translation.override(locale): if isinstance(value, dict): tran = value[code] else: tran = force_text(value) yield code, tran
def check_for_delete(view, request, object): can_delete = object.can_delete() delete_url = get_model_url(object, "delete") response = view(request, pk=object.pk) if hasattr(response, "render"): response.render() assert response.status_code in [200, 302] assert bool(delete_url in force_text(response.content)) == can_delete
def list_to_csv_response(data, title='report', header=None, widths=None): """ Make 2D list into a csv response for download data. """ response = HttpResponse(content_type="text/csv; charset=UTF-8") cw = csv.writer(response) for row in chain([header] if header else [], data): cw.writerow([force_text(s).encode(response.charset) for s in row]) return response
def ready(self): stylesSet = force_text(settings.CKEDITOR_SETTINGS.get('stylesSet')) if stylesSet != 'default:{}'.format(reverse('admin:cascade_texteditor_config')): msg = "settings.CKEDITOR_SETTINGS['stylesSet'] should be `format_lazy('default:{}', reverse_lazy('admin:cascade_texteditor_config'))`" raise ImproperlyConfigured(msg) pre_migrate.connect(self.__class__.pre_migrate, sender=self) post_migrate.connect(self.__class__.post_migrate, sender=self)
def set_value(self, value): """Serialize the value on this instance according to its type.""" if value is None: self.value = None elif isinstance(value, datetime.datetime): self.value = unicode(value.isoformat()) else: self.value = force_text(value)
def _default_text(self): if not self.use_default: note = "" else: if self.default == "": note = _('Default value: ""') elif self.choices: work = [] for x in self.choices: if x[0] in self.default: work.append(force_text(x[1])) note = ugettext('Default value: ') + u", ".join(work) else: note = _("Default value: %s") % force_text(self.default) return note
def slugify_filename(value): """ Based on django.utils.text.slugify, but allows dots and always enforces ASCII. """ value = force_text(value) value = unicodedata.normalize("NFKD", value) value = value.encode("ascii", "ignore").decode("ascii") value = re.sub(r"[^\w\s\.-]", "", value).strip().lower() return mark_safe(re.sub(r"[-\s]+", "-", value))
def ready(self): if 'cmsplugin_cascade.icon' in settings.INSTALLED_APPS: stylesSet = force_text(settings.CKEDITOR_SETTINGS.get('stylesSet')) if stylesSet != 'default:{}'.format(reverse('admin:cascade_texticon_wysiwig_config')): msg = "settings.CKEDITOR_SETTINGS['stylesSet'] should be `format_lazy('default:{}', reverse_lazy('admin:cascade_texticon_wysiwig_config'))`" raise ImproperlyConfigured(msg) pre_migrate.connect(self.__class__.pre_migrate, sender=self) post_migrate.connect(self.__class__.post_migrate, sender=self)
def iter_choices(bound_field): """ Iterator over choices """ field = bound_field.field value = bound_field.value() if value is not None: if hasattr(value, '__iter__'): value = set(force_text(v) for v in value) else: value = [force_text(value)] else: value = [] for c_value, c_label in field.widget.choices: c_value = force_text(c_value) checked = c_value in value yield c_value, force_text(c_label), checked
def get_edit_link(self, obj): if obj.pk: url = reverse( f'admin:{obj._meta.app_label}_{obj._meta.model_name}_change', args=[force_text(obj.pk)], ) return mark_safe(f'<a href="{url}">Edit {obj.filename}</a>') return mark_safe('Save and Continue editing to create a link')
def fill_utilities_sheet(self): row_number = 1 self.worksheets['utilities'].write_row( row_number, 0, ( '№', force_text(_('Utility')), force_text(_('Category')), force_text(_('Rating')), ), self.formats['header'] ) self.worksheets['utilities'].set_row(1, 30) utilities = Utility.objects.select_related('category').utilities_with_rating().iterator() for i, utility in enumerate(utilities, 1): row_number += 1 self.worksheets['utilities'].write(row_number, 0, i, self.formats['center']) utility_text_display = force_text(utility) self.worksheets['utilities'].write( row_number, 1, utility_text_display, self.formats['object_display_text'] ) category_text_display = force_text(utility.category) self.worksheets['utilities'].write( row_number, 2, category_text_display, self.formats['object_display_text'] ) rating = self.empty_value_display if utility.rating is None else utility.rating self.worksheets['utilities'].write(row_number, 3, rating, self.formats['center']) self.worksheets['utilities'].set_row( row_number, self.determinate_height_of_row(utility_text_display, category_text_display) ) self.worksheets['utilities'].set_column('A:A', 5) self.worksheets['utilities'].set_column('B:C', 50) self.worksheets['utilities'].set_column('D:D', 10)
def get_context_data(self, **kwargs): model = self.get_parent_model() has_detectchanges = None has_files = None has_comments = None has_workflow = None if model: if not hasattr(model, '_bmfmeta'): raise Http404 if not model._bmfmeta.has_activity: raise Http404 has_detectchanges = model._bmfmeta.has_detectchanges has_files = model._bmfmeta.has_files has_comments = model._bmfmeta.has_comments has_workflow = model._bmfmeta.has_workflow glob = Watch.objects.filter( user=self.request.user, active=True ).values('watch_ct').annotate(count=Count('watch_id')).order_by() configured = {} for d in glob: configured[d['watch_ct']] = d['count'] - 1 navigation = [] for ct, model in site.models.items(): if model._bmfmeta.has_activity: navigation.append({ 'name': force_text(model._meta.verbose_name_plural), 'count': configured.get(ct, 0), 'ct': ct, }) kwargs.update({ 'navigation': navigation, 'selected_ct': int(self.kwargs.get('ct', 0)), 'has_detectchanges': has_detectchanges, 'has_files': has_files, 'has_comments': has_comments, 'has_workflow': has_workflow, 'symbols': { 'workflow': ACTIVITY_WORKFLOW, 'comment': ACTIVITY_COMMENT, 'updated': ACTIVITY_UPDATED, 'file': ACTIVITY_FILE, 'created': ACTIVITY_CREATED, } }) return super(WatchMixin, self).get_context_data(**kwargs)
def list_to_csv_response(data, title='report', header=None): """ Make 2D list into a csv response for download data. """ response = HttpResponse(content_type="text/csv; charset=UTF-8") response['Content-Disposition'] = 'attachment; filename="%s.csv"' % title cw = csv.writer(response) for row in chain([header] if header else [], data): cw.writerow([force_text(s) for s in row]) return response
def create_workbook_with_sheets(self, buffer_): workbook = xlsxwriter.Workbook(buffer_) workbook.set_properties(dict( title=force_text(_('Report')), subject=force_text(self.theme), author=force_text(self.author), )) self.worksheets = dict() self.worksheets['summary'] = workbook.add_worksheet('Summary') self.worksheets['categories'] = workbook.add_worksheet('Categories') self.worksheets['utilities'] = workbook.add_worksheet('Utilities') # self.worksheets['summary'].activate() self.worksheets['utilities'].activate() self.workbook = workbook
def test_override_origin_template(self): response = self.client.get(self.url) self.assertEqual(response.status_code, 200) templates = get_templates_used(response) self.assertIn(DJANGO_ORIGIN, ','.join(templates)) self.assertIn(u'Template has been overridden', force_text(response.content))
def get_edit_link(self, obj=None): if obj.pk: url = reverse('admin:%s_%s_change' % (obj._meta.app_label, obj._meta.model_name), args=[force_text(obj.pk)]) return """<a href="{url}">{text}</a>""".format( url=url, text=_("Edit this %s separately") % obj._meta.verbose_name, ) return _("(save and continue editing to create a link)")
def get_data_dict(obj, force_text_for_value=False): data = {} for f in obj._meta.fields: if not isinstance(f, models.AutoField) and f not in obj._meta.parents.values(): value = getattr(obj, f.name) if isinstance(value, Country): value = value.code data[f.name] = (force_text(value) if force_text_for_value else value) return data
def adapt(text): a = psycopg2.extensions.adapt(force_text(text)) c = connection.connection # This is a workaround for: # https://szeryf.mvpl.eu/sentry/mv-demo/issues/7946/ if hasattr(c, '__wrapped__'): c = getattr(c, '__wrapped__') a.prepare(c) return a
def test_order_refunds_with_other_lines(rf, admin_user): shop = get_default_shop() supplier = get_default_supplier() supplier.shops.add(shop) product = create_product("sku", shop=shop, default_price=10) shop_product = product.get_shop_instance(shop=shop) shop_product.suppliers = [supplier] order = create_empty_order(shop=shop) order.full_clean() order.save() add_product_to_order(order, supplier, product, 4, 5) # Lines without quantity shouldn't affect refunds other_line = OrderLine(order=order, type=OrderLineType.OTHER, text="This random line for textual information", quantity=0) other_line.save() order.lines.add(other_line) # Lines with quantity again should be able to be refunded normally. other_line_with_quantity = OrderLine(order=order, type=OrderLineType.OTHER, text="Special service 100$/h", quantity=1, base_unit_price_value=100) other_line_with_quantity.save() order.lines.add(other_line_with_quantity) assert other_line_with_quantity.max_refundable_quantity == 1 assert other_line_with_quantity.max_refundable_amount.value == 100 order.cache_prices() order.create_payment(order.taxful_total_price) assert order.is_paid() assert order.taxful_total_price_value == 120 # 100 + 4 * 20 def get_refund_view_content(): request = apply_request_middleware(rf.get("/"), user=admin_user) view = OrderCreateRefundView.as_view() response = view(request, pk=order.pk) return BeautifulSoup(response.render().content) refund_soup = get_refund_view_content() refund_options = refund_soup.find( id="id_form-0-line_number").findAll("option") assert len( refund_options) == 4 # 1 empty line, 1 for arbitrary and 2 for lines assert len([ option for option in refund_options if "Special service 100$/h" in force_text(option) ]) == 1
def quote_value(self, value): if isinstance(value, (datetime.date, datetime.time, datetime.datetime)): return "'%s'" % value elif isinstance(value, six.string_types): return "'%s'" % six.text_type(value).replace("'", "''") elif isinstance(value, six.buffer_types): return "'%s'" % force_text(binascii.hexlify(value)) elif isinstance(value, bool): return "1" if value else "0" else: return str(value)
def quote_value(self, value): if isinstance(value, (datetime.date, datetime.time, datetime.datetime)): return "'%s'" % value elif isinstance(value, six.string_types): return "'%s'" % six.text_type(value).replace("\'", "\'\'") elif isinstance(value, six.buffer_types): return "'%s'" % force_text(binascii.hexlify(value)) elif isinstance(value, bool): return "1" if value else "0" else: return str(value)
def quote_value(self, value): if isinstance(value, (datetime.date, datetime.time, datetime.datetime)): return "'%s'" % value elif isinstance(value, str): return "'%s'" % value.replace("\'", "\'\'") elif isinstance(value, (bytes, bytearray, memoryview)): return "'%s'" % force_text(binascii.hexlify(value)) elif isinstance(value, bool): return "1" if value else "0" else: return str(value)
def adapt(text): a = psycopg2.extensions.adapt(force_text(text)) dbconfig = getattr(settings,"DATABASES", {'default': None})['default'] if not dbconfig: raise "'default' DATABASES connection is required in settings.py for djorm_ext_pgfulltext." try: pgconn= psycopg2.connect(database=dbconfig['NAME'], user=dbconfig['USER'], password=dbconfig['PASSWORD'], host=dbconfig['HOST'], port = dbconfig['PORT']) a.prepare(pgconn) finally: pgconn.close() return a
def adapt(text): connection.ensure_connection() a = psycopg2.extensions.adapt(force_text(text)) c = connection.connection # This is a workaround for https://github.com/18F/calc/issues/1498. if hasattr(c, '__wrapped__'): c = getattr(c, '__wrapped__') a.prepare(c) return a
def test_view_make_report_throught_GET(self): request = self.factory.get(self.url_polls_make_report) request.user = self.active_superuser response = self.PollAdmin.view_make_report(request) self.assertEqual(response.status_code, 200) self.assertEqual(response.template_name, 'polls/admin/report.html') self.assertEqual(force_text(response.context_data['title']), 'Make a report about polls') self.assertEqual(response.context_data['current_app'], apps.get_app_config(Poll._meta.app_label)) self.assertIsInstance(response.context_data['django_admin_media'], widgets.Media)