Python swapper.load_model() Examples
The following are 30
code examples of swapper.load_model().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
swapper
, or try the search function
.
Example #1
Source File: create_guest.py From omniport-backend with GNU General Public License v3.0 | 6 votes |
def create_guest(): Person = swapper.load_model('kernel', 'person') password = ''.join(random.choice(string.ascii_letters) for i in range(10)) guest_user = User.objects.create_user( username=settings.GUEST_USERNAME, password=password ) guest_person, _ = Person.objects.get_or_create( user=guest_user, short_name=settings.GUEST_USERNAME, full_name=settings.GUEST_USERNAME ) Guest = swapper.load_model('kernel', 'Guest') Guest.objects.get_or_create(person=guest_person, start_date=datetime.date.today()) return guest_user
Example #2
Source File: models.py From openwisp-radius with GNU General Public License v3.0 | 6 votes |
def send_token(self): OrganizationUser = swapper.load_model('openwisp_users', 'OrganizationUser') org_user = OrganizationUser.objects.filter(user=self.user).first() if not org_user: raise exceptions.NoOrgException( 'User {} is not member ' 'of any organization'.format(self.user) ) org_radius_settings = org_user.organization.radius_settings message = _('{} verification code: {}').format( org_radius_settings.organization.name, self.token ) sms_message = SmsMessage( body=message, from_phone=str(org_radius_settings.sms_sender), to=[str(self.user.phone_number)], ) sms_message.send(meta_data=org_radius_settings.sms_meta_data)
Example #3
Source File: models.py From openwisp-users with BSD 3-Clause "New" or "Revised" License | 6 votes |
def organizations_pk(self): """ returns primary keys of organizations the user is associated to """ logger.warn( "User.organizations_pk is deprecated in favor of User.organizations_dict" " and will be removed in a future version" ) manager = load_model('openwisp_users', 'OrganizationUser').objects qs = ( manager.filter(user=self, organization__is_active=True) .select_related() .only('organization_id') .values_list('organization_id') ) return qs
Example #4
Source File: models.py From openwisp-ipam with BSD 3-Clause "New" or "Revised" License | 6 votes |
def _read_subnet_data(self, reader): subnet_model = load_model('openwisp_ipam', 'Subnet') subnet_name = next(reader)[0].strip() subnet_value = next(reader)[0].strip() subnet_org = self._get_or_create_org(next(reader)[0].strip()) try: subnet = subnet_model.objects.get( subnet=subnet_value, organization=subnet_org ) except ValidationError as e: raise CsvImportException(str(e)) except subnet_model.DoesNotExist: try: subnet = subnet_model( name=subnet_name, subnet=subnet_value, organization=subnet_org ) subnet.full_clean() subnet.save() except ValidationError as e: raise CsvImportException(str(e)) return subnet
Example #5
Source File: models.py From openwisp-ipam with BSD 3-Clause "New" or "Revised" License | 6 votes |
def _read_ipaddress_data(self, reader, subnet): ipaddress_model = load_model('openwisp_ipam', 'IpAddress') ipaddress_list = [] for row in reader: if not ipaddress_model.objects.filter( subnet=subnet, ip_address=row[0].strip(), ).exists(): instance = ipaddress_model( subnet=subnet, ip_address=row[0].strip(), description=row[1].strip(), ) try: instance.full_clean() except ValueError as e: raise CsvImportException(str(e)) ipaddress_list.append(instance) for ip in ipaddress_list: ip.save()
Example #6
Source File: models.py From openwisp-ipam with BSD 3-Clause "New" or "Revised" License | 6 votes |
def export_csv(self, subnet_id, writer): ipaddress_model = load_model('openwisp_ipam', 'IpAddress') subnet = load_model('openwisp_ipam', 'Subnet').objects.get(pk=subnet_id) writer.writerow([subnet.name]) writer.writerow([subnet.subnet]) writer.writerow('') fields = [ ipaddress_model._meta.get_field('ip_address'), ipaddress_model._meta.get_field('description'), ] writer.writerow(field.name for field in fields) for obj in subnet.ipaddress_set.all(): row = [] for field in fields: row.append(str(getattr(obj, field.name))) writer.writerow(row)
Example #7
Source File: models.py From django-ipam with BSD 3-Clause "New" or "Revised" License | 6 votes |
def clean(self): if not self.subnet: return allowed_master = None for subnet in load_model('django_ipam', 'Subnet').objects.filter().values(): if self.id == subnet['id']: continue if ip_network(self.subnet).overlaps(subnet['subnet']): if not self.master_subnet and not subnet['subnet'].subnet_of(ip_network(self.subnet)): raise ValidationError({ 'subnet': _('Subnet overlaps with %s') % subnet['subnet'] }) if not allowed_master or subnet['subnet'].subnet_of(allowed_master): allowed_master = subnet['subnet'] if self.master_subnet: if not ip_network(self.subnet).subnet_of(ip_network(self.master_subnet.subnet)): raise ValidationError({ 'master_subnet': _('Invalid master subnet') }) if ip_network(self.master_subnet.subnet) != allowed_master and not \ allowed_master.subnet_of(ip_network(self.subnet)): raise ValidationError({ 'subnet': _('Subnet overlaps with %s') % allowed_master })
Example #8
Source File: models.py From openwisp-controller with GNU General Public License v3.0 | 6 votes |
def auto_add_to_devices(self): """ When ``auto_add`` is ``True``, adds the credentials to each relevant ``Device`` and ``DeviceConnection`` objects """ if not self.auto_add: return device_model = load_model('config', 'Device') devices = device_model.objects.exclude(config=None) org = self.organization if org: devices = devices.filter(organization=org) # exclude devices which have been already added devices = devices.exclude(deviceconnection__credentials=self) for device in devices: DeviceConnection = load_model('connection', 'DeviceConnection') conn = DeviceConnection(device=device, credentials=self, enabled=True) conn.full_clean() conn.save()
Example #9
Source File: models.py From django-ipam with BSD 3-Clause "New" or "Revised" License | 6 votes |
def _read_ipaddress_data(self, reader, subnet): ipaddress_model = load_model('django_ipam', 'IpAddress') ipaddress_list = [] for row in reader: if not ipaddress_model.objects.filter(subnet=subnet, ip_address=row[0].strip(), description=row[1].strip()).exists(): instance = ipaddress_model(subnet=subnet, ip_address=row[0].strip(), description=row[1].strip()) try: instance.full_clean() except ValueError as e: raise CsvImportException(str(e)) ipaddress_list.append(instance) for ip in ipaddress_list: ip.save()
Example #10
Source File: apps.py From openwisp-controller with GNU General Public License v3.0 | 6 votes |
def ready(self): """ connects the ``config_modified`` signal to the ``update_config`` celery task which will be executed in the background """ config_modified.connect( self.config_modified_receiver, dispatch_uid='connection.update_config' ) Config = load_model('config', 'Config') Credentials = load_model('connection', 'Credentials') post_save.connect( Credentials.auto_add_credentials_to_device, sender=Config, dispatch_uid='connection.auto_add_credentials', )
Example #11
Source File: models.py From django-ipam with BSD 3-Clause "New" or "Revised" License | 6 votes |
def _read_subnet_data(self, reader): subnet_model = load_model('django_ipam', 'Subnet') subnet_name = next(reader)[0].strip() subnet_value = next(reader)[0].strip() try: subnet = subnet_model.objects.get(name=subnet_name, subnet=subnet_value) except ValidationError as e: raise CsvImportException(str(e)) except subnet_model.DoesNotExist: try: subnet = subnet_model(name=subnet_name, subnet=subnet_value) subnet.full_clean() subnet.save() except ValidationError as e: raise CsvImportException(str(e)) return subnet
Example #12
Source File: get_role.py From omniport-backend with GNU General Public License v3.0 | 5 votes |
def get_role(person, role_name, active_status=ActiveStatus.ANY, silent=False, *args, **kwargs): """ Get a role corresponding to a person :param person: an instance of the Person model whose roles are sought :param role_name: the name of the role class whose instance is required :param active_status: whether the role was, is, isn't or will be active :param silent: whether to fail silently or raise exceptions :return: the role, if the person fulfills it :raise: Role.DoesNotExist, if the given role is not fulfilled by the person :raise: ImproperlyConfigured, if the name of the role class is incorrect """ is_custom_role = kwargs.get('is_custom_role', False) try: if is_custom_role: Role = swapper.load_model( role_name.split('.')[0], role_name.split('.')[1], ) else: Role = swapper.load_model('kernel', role_name) try: query_set = Role.objects_filter(active_status) role = query_set.get(person=person) return role except Role.DoesNotExist: if not silent: raise except ImproperlyConfigured: if not silent: raise return None
Example #13
Source File: test_swapper.py From django-swappable-models with MIT License | 5 votes |
def test_swap_fields(self): Type = swapper.load_model('default_app', 'Type') fields = dict( (field.name, field) for field in Type._meta.fields ) self.assertIn('code', fields)
Example #14
Source File: faculty_member.py From omniport-backend with GNU General Public License v3.0 | 5 votes |
def department(self): """ Return the department of the branch :return: the department object """ if self.entity_content_type.name == 'centre': Class = swapper.load_model('shell', 'Centre') else: Class = swapper.load_model('shell', 'Department') department = Class.objects.get(id=self.entity_object_id) return department
Example #15
Source File: course.py From omniport-backend with GNU General Public License v3.0 | 5 votes |
def department(self): """ Return the department of the branch :return: the department object """ if self.entity_content_type.name == 'centre': Class = swapper.load_model('shell', 'Centre') else: Class = swapper.load_model('shell', 'Department') department = Class.objects.get(id=self.entity_object_id) return department
Example #16
Source File: models.py From django-ipam with BSD 3-Clause "New" or "Revised" License | 5 votes |
def request_ip(self, options=None): if options is None: options = {} ip = self.get_first_available_ip() if not ip: return None ip_address = load_model('django_ipam', 'IpAddress')(ip_address=ip, subnet=self, **options) ip_address.full_clean() ip_address.save() return ip_address
Example #17
Source File: models.py From django-ipam with BSD 3-Clause "New" or "Revised" License | 5 votes |
def export_csv(self, subnet_id, writer): ipaddress_model = load_model('django_ipam', 'IpAddress') subnet = load_model('django_ipam', 'Subnet').objects.get(pk=subnet_id) writer.writerow([subnet.name, ]) writer.writerow([subnet.subnet, ]) writer.writerow('') fields = [ipaddress_model._meta.get_field('ip_address'), ipaddress_model._meta.get_field('description')] writer.writerow(field.name for field in fields) for obj in subnet.ipaddress_set.all(): row = [] for field in fields: row.append(str(getattr(obj, field.name))) writer.writerow(row)
Example #18
Source File: models.py From openwisp-radius with GNU General Public License v3.0 | 5 votes |
def save_user(self, user): OrganizationUser = swapper.load_model('openwisp_users', 'OrganizationUser') user.save() self.users.add(user) if OrganizationUser.objects.filter( user=user, organization=self.organization ).exists(): return obj = OrganizationUser( user=user, organization=self.organization, is_admin=False ) obj.full_clean() obj.save()
Example #19
Source File: models.py From openwisp-radius with GNU General Public License v3.0 | 5 votes |
def clean(self): if not hasattr(self, 'user'): return if self.user.is_active: logger.warning('user {} is already active'.format(self.user)) raise ValidationError(_('This user is already active.')) if not self.user.phone_number: logger.warning('user {} does not have a ' 'phone number'.format(self.user)) raise ValidationError(_('This user does not have a phone number.')) date_start = timezone.localdate() date_end = date_start + timedelta(days=1) PhoneToken = load_model('PhoneToken') qs = PhoneToken.objects.filter(created__range=[date_start, date_end]) # limit generation of tokens per day by user user_token_count = qs.filter(user=self.user).count() if user_token_count >= app_settings.SMS_TOKEN_MAX_USER_DAILY: logger.warning( 'user {} has reached the maximum ' 'daily SMS limit'.format(self.user) ) raise ValidationError(_('Maximum daily limit reached.')) # limit generation of tokens per day by ip ip_token_count = qs.filter(ip=self.ip).count() if ip_token_count >= app_settings.SMS_TOKEN_MAX_IP_DAILY: logger.warning( logger.warning( 'user {} has reached the maximum ' 'daily SMS limit from ip address {}'.format(self.user, self.ip) ) ) raise ValidationError( _('Maximum daily limit reached ' 'from this ip address.') )
Example #20
Source File: utils.py From openwisp-radius with GNU General Public License v3.0 | 5 votes |
def load_model(model): return swapper.load_model('openwisp_radius', model)
Example #21
Source File: utils.py From openwisp-radius with GNU General Public License v3.0 | 5 votes |
def create_default_groups(organization): RadiusGroup = load_model('RadiusGroup') RadiusGroupCheck = load_model('RadiusGroupCheck') default = RadiusGroup( organization_id=organization.pk, name='{}-users'.format(organization.slug), description='Regular users', default=True, ) default.save() check = RadiusGroupCheck( group_id=default.id, groupname=default.name, attribute=SESSION_TIME_ATTRIBUTE, op=':=', value=DEFAULT_SESSION_TIME_LIMIT, ) check.save() check = RadiusGroupCheck( group_id=default.id, groupname=default.name, attribute=SESSION_TRAFFIC_ATTRIBUTE, op=':=', value=DEFAULT_SESSION_TRAFFIC_LIMIT, ) check.save() power_users = RadiusGroup( organization_id=organization.pk, name='{}-power-users'.format(organization.slug), description='Users with less restrictions', default=False, ) power_users.save()
Example #22
Source File: apps.py From openwisp-radius with GNU General Public License v3.0 | 5 votes |
def connect_signals(self): OrganizationUser = swapper.load_model('openwisp_users', 'OrganizationUser') Organization = swapper.load_model('openwisp_users', 'Organization') User = get_user_model() post_save.connect( create_default_groups_handler, sender=Organization, dispatch_uid='create_default_groups', ) post_save.connect( update_user_related_records, sender=User, dispatch_uid='update_user_related_records', ) post_save.connect( set_default_group_handler, sender=OrganizationUser, dispatch_uid='set_default_group', ) pre_save.connect( organization_pre_save, sender=Organization, dispatch_uid='openwisp_radius_org_pre_save', ) post_save.connect( organization_post_save, sender=Organization, dispatch_uid='openwisp_radius_org_post_save', )
Example #23
Source File: test_swapper.py From django-swappable-models with MIT License | 5 votes |
def test_swap_create(self): Type = swapper.load_model('default_app', 'Type') Item = swapper.load_model('default_app', 'Item') Item.objects.create( type=Type.objects.create( name="Type 1", code="type-1", ), name="Item 1", ) self.assertEqual(Item.objects.count(), 1) item = Item.objects.all()[0] self.assertEqual(item.type.code, "type-1")
Example #24
Source File: test_swapper.py From django-swappable-models with MIT License | 5 votes |
def test_not_installed(self): Invalid = swapper.load_model("invalid_app", "Invalid", required=False) self.assertIsNone(Invalid) with self.assertRaises(ImproperlyConfigured): swapper.load_model("invalid_app", "Invalid", required=True)
Example #25
Source File: test_swapper.py From django-swappable-models with MIT License | 5 votes |
def test_create(self): Type = swapper.load_model('default_app', 'Type') Item = swapper.load_model('default_app', 'Item') Item.objects.create( type=Type.objects.create(name="Type 1"), name="Item 1", ) self.assertEqual(Item.objects.count(), 1) item = Item.objects.all()[0] self.assertEqual(item.type.name, "Type 1")
Example #26
Source File: test_swapper.py From django-swappable-models with MIT License | 5 votes |
def test_fields(self): Type = swapper.load_model('default_app', 'Type') fields = dict( (field.name, field) for field in Type._meta.fields ) self.assertIn('name', fields)
Example #27
Source File: apps.py From openwisp-controller with GNU General Public License v3.0 | 5 votes |
def __setmodels__(self): self.config_model = load_model('config', 'Config') self.vpnclient_model = load_model('config', 'VpnClient')
Example #28
Source File: models.py From openwisp-controller with GNU General Public License v3.0 | 5 votes |
def auto_add_credentials_to_device(cls, instance, created, **kwargs): """ Adds relevant credentials as ``DeviceConnection`` when a device is created, this is called from a post_save signal receiver hooked to the ``Config`` model (why ``Config`` and not ``Device``? because at the moment we can automatically create a DeviceConnection if we have a ``Config`` object) """ if not created: return device = instance.device # select credentials which # - are flagged as auto_add # - belong to the same organization of the device # OR # belong to no organization (hence are shared) conditions = models.Q(organization=device.organization) | models.Q( organization=None ) credentials = cls.objects.filter(conditions).filter(auto_add=True) for cred in credentials: DeviceConnection = load_model('connection', 'DeviceConnection') conn = DeviceConnection(device=device, credentials=cred, enabled=True) conn.full_clean() conn.save()
Example #29
Source File: apps.py From openwisp-controller with GNU General Public License v3.0 | 5 votes |
def __setmodels__(self): self.location_model = swapper.load_model('geo', 'Location')
Example #30
Source File: models.py From openwisp-ipam with BSD 3-Clause "New" or "Revised" License | 5 votes |
def request_ip(self, options=None): if options is None: options = {} ip = self.get_next_available_ip() if not ip: return None ip_address = load_model('openwisp_ipam', 'IpAddress')( ip_address=ip, subnet=self, **options ) ip_address.full_clean() ip_address.save() return ip_address