示例#1
0
    def test_callable_path(self):
        path = os.path.dirname(__file__)

        def generate_path():
            return path

        field = FilePathField(path=generate_path)
        self.assertEqual(field.path(), path)
        self.assertEqual(field.formfield().path, path)
示例#2
0
class Seeker(Model):
    user = OneToOneField(settings.AUTH_USER_MODEL,
                         primary_key=True,
                         on_delete=CASCADE)
    gender = CharField(max_length=6, null=True)
    dob = DateField(null=True)
    nationality = CharField(max_length=10, null=True)
    visa_type = CharField(max_length=10, null=True)
    #contact
    phone_number = CharField(max_length=10, null=True, unique=True)
    phone_country_code = CharField(max_length=5, null=True)
    near_station = JSONField(default=near_station)
    #skill
    education = CharField(max_length=20, null=True)
    certificate = ListCharField(base_field=CharField(max_length=10),
                                size=10,
                                max_length=(10 * 11),
                                null=True)
    japanese_lang_level = IntegerField(null=True)
    jlpt_score = IntegerField(null=True)
    lang_known = ListCharField(base_field=CharField(max_length=10),
                               size=10,
                               max_length=(10 * 11),
                               null=True)
    job_interested = ListCharField(base_field=CharField(max_length=10),
                                   size=10,
                                   max_length=(10 * 11),
                                   null=True)
    job_experienced = ListCharField(base_field=CharField(max_length=10),
                                    size=10,
                                    max_length=(10 * 11),
                                    null=True)
    current_hourly_salary = IntegerField(null=True)
    #file path
    id_photo_path = FilePathField(blank=True, null=True)
    profile_pic_path = FilePathField(blank=True, null=True)
    residence_card_path = FilePathField(blank=True, null=True)
    intro_voice_path = FilePathField(blank=True, null=True)
    #time
    created_at = DateTimeField(auto_now_add=True)
    updated_at = DateTimeField(auto_now=True)
    last_application = DateTimeField(null=True)
    last_login = DateTimeField(auto_now=True)
    is_disabled = BooleanField(default=False)
    disp_lang = CharField(max_length=10, null=True)
    seeker_status = CharField(max_length=10, null=True)
    urgent = BooleanField(default=False)
    #token
    fb_access_token = CharField(max_length=255, null=True)

    def __str__(self):
        return self.user.email
示例#3
0
class TestModelFields(Model):
    big_int = BigIntegerField()
    yesno = BooleanField()
    title = CharField(max_length=150)
    csv_data = CommaSeparatedIntegerField(max_length=255)
    when = DateField()
    when_accurate = DateTimeField()
    amount = DecimalField(max_digits=8, decimal_places=4)
    email = EmailField()
    upload = FileField(upload_to='test')
    path = FilePathField(path=d.APP_DIR, recursive=False, match=".json$")
    inaccurate = FloatField()
    img = ImageField(upload_to='test')
    ip = IPAddressField()
    better_ip = GenericIPAddressField(protocol='both')
    yesnomaybe = NullBooleanField(default=None)
    posint = PositiveIntegerField()
    small_posint = PositiveSmallIntegerField()
    slug = SlugField()
    small_int = SmallIntegerField()
    content = TextField()
    when_time = TimeField()
    web_address = URLField()
    user = ForeignKey('auth.User')
    groups = ManyToManyField('auth.Group')
    one_to_one = OneToOneField('auth.Permission')

    class Meta:
        verbose_name = 'test model fields'
        verbose_name_plural = 'test model fields'
示例#4
0
class ComplicatedTestModel(Model):
    char_field = CharField(max_length=32)
    bigint_field = BigIntegerField()
    boolean_field = BooleanField()
    commaseparatedinteger_field = CommaSeparatedIntegerField(max_length=32)
    date_field = DateField()
    datetime_field = DateTimeField()
    decimal_field = DecimalField(decimal_places=2, max_digits=20)
    email_field = EmailField()
    file_field = FileField()
    filepath_field = FilePathField(path="/home")
    float_field = FloatField()
    image_field = ImageField()
    integer_field = IntegerField()
    ipaddress_field = IPAddressField()
    nullboolean_field = NullBooleanField()
    positiveinteger_field = PositiveIntegerField()
    positivesmallinteger_field = PositiveSmallIntegerField()
    slug_field = SlugField()
    smallinteger_field = SmallIntegerField()
    text_field = TextField()
    url_field = URLField()

    def auto_populate(self):
        self.char_field = 'foo'
        self.bigint_field = 2379238742398
        self.boolean_field = True
        self.commaseparatedinteger_field = '1, 2, 3, 4'
        self.date_field = datetime.datetime(2014, 1, 1)
        self.datetime_field = datetime.datetime(2014, 1, 1)
        self.decimal_field = 3.14
        self.email_field = '*****@*****.**'
        self.file_field = 'test.txt'
        self.filepath_field = 'test.txt'
        self.float_field = 3.14
        self.image_field = 'test.png'
        self.integer_field = 1024
        self.ipaddress_field = '8.8.8.8'
        self.nullboolean_field = None
        self.positiveinteger_field = 1024
        self.positivesmallinteger_field = 1024
        self.slug_field = 'eat-slugs-all-day-long'
        self.smallinteger_field = 3
        self.text_field = 'foo bar var\nvar bar foo'
        self.url_field = 'http://example.com'
示例#5
0
class Course(models.Model):
    course_org = models.ForeignKey(CourseOrg,
                                   verbose_name='课程机构',
                                   null=True,
                                   blank=True,
                                   on_delete=models.CASCADE)
    name = models.CharField(max_length=50, verbose_name='课程名')
    desc = models.CharField(max_length=300, verbose_name='课程描述')
    detail = models.TextField(verbose_name='课程详情')
    teacher = models.ForeignKey(Teacher,
                                verbose_name='课程讲师',
                                null=True,
                                blank=True,
                                on_delete=models.CASCADE)
    is_banner = models.BooleanField(default=False, verbose_name='是否轮播')
    degree = models.CharField(choices=(('cj', '初级'), ('zj', '中级'), ('gj',
                                                                    '高级')),
                              max_length=20)
    learn_times = models.IntegerField(default=20, verbose_name='学习时长')
    student = models.IntegerField(default=0, verbose_name='学习人数')
    fav_nums = models.IntegerField(default=0, verbose_name='点赞人数')
    category = models.CharField(default='后端开发',
                                max_length=50,
                                verbose_name='课程类别')
    image = models.ImageField(upload_to='courses/%Y/%m', verbose_name='封面')
    tag = models.CharField(default='', max_length=20, verbose_name='课程标签')
    click_name = models.IntegerField(default=0, verbose_name='点击数')
    add_time = models.DateTimeField(default=datetime.now, verbose_name='添加时间')
    FilePathField(path="/home/images", match="foo.*", recursive=True)

    class Meta:
        verbose_name = '课程'
        verbose_name_plural = verbose_name

    def get_ZJ_nums(self):
        #获取章节总数
        return self.lesson_set.all().count()

    def get_learn_user(self):
        return self.usercourse_set.all()[:5]

    def __unicode__(self):
        return self.name
示例#6
0
class BootSource(CleanSave, TimestampedModel):
    """A source for boot resources."""

    class Meta(DefaultMeta):
        """Needed for South to recognize this model."""

    url = URLField(
        blank=False, unique=True, help_text="The URL of the BootSource.")

    keyring_filename = FilePathField(
        blank=True, max_length=4096,
        help_text="The path to the keyring file for this BootSource.")

    keyring_data = EditableBinaryField(
        blank=True,
        help_text="The GPG keyring for this BootSource, as a binary blob.")

    def clean(self, *args, **kwargs):
        super(BootSource, self).clean(*args, **kwargs)

        # You have to specify one of {keyring_data, keyring_filename}.
        if len(self.keyring_filename) == 0 and len(self.keyring_data) == 0:
            raise ValidationError(
                "One of keyring_data or keyring_filename must be specified.")

        # You can have only one of {keyring_filename, keyring_data}; not
        # both.
        if len(self.keyring_filename) > 0 and len(self.keyring_data) > 0:
            raise ValidationError(
                "Only one of keyring_filename or keyring_data can be "
                "specified.")

    def to_dict_without_selections(self):
        """Return the current `BootSource` as a dict, without including any
        `BootSourceSelection` items.

        The dict will contain the details of the `BootSource`.

        If the `BootSource` has keyring_data, that data will be returned
        base64 encoded. Otherwise the `BootSource` will have a value in
        its keyring_filename field, and that file's contents will be
        base64 encoded and returned.
        """
        if len(self.keyring_data) > 0:
            keyring_data = self.keyring_data
        else:
            with open(self.keyring_filename, 'rb') as keyring_file:
                keyring_data = keyring_file.read()
        return {
            "url": self.url,
            "keyring_data": bytes(keyring_data),
            "selections": [],
            }

    def compare_dict_without_selections(self, other):
        """Compare this `BootSource`, as a dict, to another, as a dict.

        Only the keys ``url`` and ``keyring_data`` are relevant.
        """
        keys = "url", "keyring_data"
        this = self.to_dict_without_selections()
        return all(this[key] == other[key] for key in keys)

    def to_dict(self):
        """Return the current `BootSource` as a dict.

        The dict will contain the details of the `BootSource` and all
        its `BootSourceSelection` items.

        If the `BootSource` has keyring_data, that data will be returned
        base64 encoded. Otherwise the `BootSource` will have a value in
        its keyring_filename field, and that file's contents will be
        base64 encoded and returned.
        """
        data = self.to_dict_without_selections()
        data['selections'] = [
            selection.to_dict()
            for selection in self.bootsourceselection_set.all()
            ]
        # Always download all bootloaders from the stream. This will allow
        # machines to boot and get a 'Booting under direction of MAAS' message
        # even if boot images for that arch haven't downloaded yet.
        for bootloader in self.bootsourcecache_set.exclude(
                bootloader_type=None):
            data['selections'].append({
                'os': bootloader.os,
                'release': bootloader.bootloader_type,
                'arches': [bootloader.arch],
                'subarches': ['*'],
                'labels': ['*'],
            })
        return data
示例#7
0
class BlockDevice(CleanSave, TimestampedModel):
    """A block device attached to a node."""
    class Meta(DefaultMeta):
        """Needed for South to recognize this model."""
        unique_together = ("node", "name")
        ordering = ["id"]

    objects = BlockDeviceManager()

    node = ForeignKey('Node', null=False, editable=False, on_delete=CASCADE)

    name = CharField(max_length=255,
                     blank=False,
                     help_text="Name of block device. (e.g. sda)")

    id_path = FilePathField(
        blank=True,
        null=True,
        max_length=4096,
        help_text="Path of by-id alias. (e.g. /dev/disk/by-id/wwn-0x50004...)")

    size = BigIntegerField(
        blank=False,
        null=False,
        validators=[MinValueValidator(MIN_BLOCK_DEVICE_SIZE)],
        help_text="Size of block device in bytes.")

    block_size = IntegerField(
        blank=False,
        null=False,
        validators=[MinValueValidator(MIN_BLOCK_DEVICE_BLOCK_SIZE)],
        help_text="Size of a block on the device in bytes.")

    tags = ArrayField(TextField(), blank=True, null=True, default=list)

    def get_name(self):
        """Return the name.

        This exists so `VirtualBlockDevice` can override this method.
        """
        return self.name

    def get_node(self):
        """Return the name."""
        return self.node

    @property
    def path(self):
        # Path is persistent and set by curtin on deploy.
        return "/dev/disk/by-dname/%s" % self.get_name()

    @property
    def type(self):
        # Circular imports, since ISCSIBlockDevice, PhysicalBlockDevice and
        # VirtualBlockDevice extend from this calss.
        from maasserver.models.iscsiblockdevice import ISCSIBlockDevice
        from maasserver.models.physicalblockdevice import PhysicalBlockDevice
        from maasserver.models.virtualblockdevice import VirtualBlockDevice
        actual_instance = self.actual_instance
        if isinstance(actual_instance, ISCSIBlockDevice):
            return "iscsi"
        elif isinstance(actual_instance, PhysicalBlockDevice):
            return "physical"
        elif isinstance(actual_instance, VirtualBlockDevice):
            return "virtual"
        else:
            raise ValueError(
                "BlockDevice is not a subclass of "
                "ISCSIBlockDevice, PhysicalBlockDevice or VirtualBlockDevice")

    @property
    def actual_instance(self):
        """Return the instance as its correct type.

        By default all references from Django will be to `BlockDevice`, when
        the native type `ISCSIBlockDevice`, `PhysicalBlockDevice` or
        `VirtualBlockDevice` is needed use this property to get its actual
        instance.
        """
        # Circular imports, since ISCSIBlockDevice, PhysicalBlockDevice and
        # VirtualBlockDevice extend from this calss.
        from maasserver.models.iscsiblockdevice import ISCSIBlockDevice
        from maasserver.models.physicalblockdevice import PhysicalBlockDevice
        from maasserver.models.virtualblockdevice import VirtualBlockDevice
        if (isinstance(self, ISCSIBlockDevice)
                or isinstance(self, PhysicalBlockDevice)
                or isinstance(self, VirtualBlockDevice)):
            return self
        try:
            return self.iscsiblockdevice
        except:
            try:
                return self.physicalblockdevice
            except PhysicalBlockDevice.DoesNotExist:
                try:
                    return self.virtualblockdevice
                except VirtualBlockDevice.DoesNotExist:
                    pass
        return self

    def get_effective_filesystem(self):
        """Return the filesystem that is placed on this block device."""
        return get_effective_filesystem(self)

    def get_partitiontable(self):
        """Returns this device's partition table (or None, if none exists."""
        partition_tables = self.partitiontable_set.all()
        if len(partition_tables) > 0:
            return partition_tables[0]
        else:
            return None

    def display_size(self, include_suffix=True):
        return human_readable_bytes(self.size, include_suffix=include_suffix)

    def add_tag(self, tag):
        """Add tag to block device."""
        if tag not in self.tags:
            self.tags = self.tags + [tag]

    def remove_tag(self, tag):
        """Remove tag from block device."""
        if tag in self.tags:
            tags = self.tags.copy()
            tags.remove(tag)
            self.tags = tags

    @property
    def used_size(self):
        """Return the used size on the block device."""
        return self.get_used_size()

    @property
    def available_size(self):
        """Return the available size on the block device."""
        return self.get_available_size()

    @property
    def used_for(self):
        """Return what the block device is being used for."""
        return used_for(self)

    def __str__(self):
        return '{size} attached to {node}'.format(size=human_readable_bytes(
            self.size),
                                                  node=self.node)

    def get_block_size(self):
        """Return the block size for the block device."""
        return self.block_size

    def get_used_size(self):
        """Return the used size on the block device."""
        filesystem = self.get_effective_filesystem()
        if filesystem is not None:
            return self.size
        partitiontable = self.get_partitiontable()
        if partitiontable is not None:
            return partitiontable.get_used_size()
        return 0

    def get_available_size(self):
        """Return the available size on the block device."""
        filesystem = self.get_effective_filesystem()
        if filesystem is not None:
            return 0
        partitiontable = self.get_partitiontable()
        if partitiontable is not None:
            return partitiontable.get_available_size()
        return self.size

    def is_boot_disk(self):
        """Return true if block device is the boot disk."""
        boot_disk = self.node.get_boot_disk()
        return boot_disk.id == self.id

    def create_partition(self):
        """Creates a partition that uses the whole disk."""
        if self.get_partitiontable() is not None:
            raise ValueError(
                "Cannot call create_partition_if_boot_disk when a "
                "partition table already exists on the block device.")
        # Circular imports.
        from maasserver.models.partitiontable import PartitionTable
        partition_table = PartitionTable.objects.create(block_device=self)
        return partition_table.add_partition()

    def create_partition_if_boot_disk(self):
        """Creates a partition that uses the whole disk if this block device
        is the boot disk."""
        if self.is_boot_disk():
            return self.create_partition()
        else:
            return None

    def delete(self):
        """Delete the block device.

        If this block device is part of a filesystem group then it cannot be
        deleted.
        """
        filesystem = self.get_effective_filesystem()
        if filesystem is not None:
            filesystem_group = filesystem.filesystem_group
            if filesystem_group is not None:
                raise ValidationError(
                    "Cannot delete block device because its part of "
                    "a %s." % filesystem_group.get_nice_name())
        super(BlockDevice, self).delete()

    @staticmethod
    def _get_block_name_from_idx(idx, prefix='sd'):
        """Calculate a block name based on the `idx`.

        Drive#  Name
        0	    sda
        25	    sdz
        26	    sdaa
        27	    sdab
        51	    sdaz
        52	    sdba
        53	    sdbb
        701	    sdzz
        702	    sdaaa
        703	    sdaab
        18277   sdzzz
        """
        name = ""
        while idx >= 0:
            name = string.ascii_lowercase[idx % 26] + name
            idx = (idx // 26) - 1
        return prefix + name

    @staticmethod
    def _get_idx_from_block_name(name, prefix='sd'):
        """Calculate a idx based on `name`.

        Name   Drive#
        sda    0
        sdz    25
        sdaa   26
        sdab   27
        sdaz   51
        sdba   52
        sdbb   53
        sdzz   701
        sdaaa  702
        sdaab  703
        sdzzz  18277
        """
        match = re.match('%s([a-z]+)' % prefix, name)
        if match is None:
            return None
        else:
            idx = 0
            suffix = match.group(1)
            for col, char in enumerate(reversed(suffix)):
                digit = ord(char) + (0 if col == 0 else 1) - ord("a")
                idx += digit * (26**col)
            return idx
示例#8
0
 def test_FilePathField(self):
     lazy_func = lazy(lambda: "tests.py", str)
     self.assertIsInstance(FilePathField().get_prep_value(lazy_func()), str)
     lazy_func = lazy(lambda: 0, int)
     self.assertIsInstance(FilePathField().get_prep_value(lazy_func()), str)
示例#9
0
class Test(Model):

    id = UUIDField(
        primary_key=True,
        default=uuid4,
        editable=False,
    )

    label = CharField(
        verbose_name=_("label"),
        max_length=32,
        blank=False,
        db_index=True,
        unique=True,
    )

    category = ForeignKey(
        verbose_name=_("category"),
        related_name="test_set",
        to=Category,
        null=True,
        blank=True,
        db_index=True,
        on_delete=PROTECT,
    )

    theme_set = ManyToManyField(
        verbose_name=_("theme_set"),
        related_name="test_set",
        to=Theme,
        blank=True,
    )

    category2 = ForeignKey(
        verbose_name=_("category 2"),
        related_name="test2_set",
        to=Category,
        null=True,
        blank=True,
        db_index=True,
        on_delete=CASCADE,
    )

    theme_set2 = ManyToManyField(
        verbose_name=_("theme_set 2"),
        related_name="test2_set",
        to=Theme,
        blank=True,
    )

    category3 = ForeignKey(
        verbose_name=_("category 3"),
        related_name="test3_set",
        to=Category,
        null=True,
        blank=True,
        db_index=True,
        on_delete=CASCADE,
    )

    theme_set3 = ManyToManyField(
        verbose_name=_("theme_set 3"),
        related_name="test3_set",
        to=Theme,
        blank=True,
    )

    category4 = ForeignKey(
        verbose_name=_("category 4"),
        related_name="test4_set",
        to=Category,
        null=True,
        blank=True,
        db_index=True,
        on_delete=CASCADE,
    )

    theme_set4 = ManyToManyField(
        verbose_name=_("theme_set 4"),
        related_name="test4_set",
        to=Theme,
        blank=True,
    )

    category5 = ForeignKey(
        verbose_name=_("category 5"),
        related_name="test5_set",
        to=Category,
        null=True,
        blank=True,
        db_index=True,
        on_delete=CASCADE,
    )

    theme_set5 = ManyToManyField(
        verbose_name=_("theme_set 5"),
        related_name="test5_set",
        to=Theme,
        blank=True,
    )

    category6 = ForeignKey(
        verbose_name=_("category 6"),
        related_name="test6_set",
        to=Category,
        null=True,
        blank=True,
        db_index=True,
        on_delete=CASCADE,
    )

    theme_set6 = ManyToManyField(
        verbose_name=_("theme_set 6"),
        related_name="test6_set",
        to=Theme,
        blank=True,
    )

    tag_set = ManyToManyField(
        verbose_name=_("theme_set"),
        related_name="test_set",
        to=Tag,
        through="Mapping",
        blank=True,
    )

    number = PositiveSmallIntegerField(
        verbose_name=_("number"),
        unique=True,
    )

    percent = DecimalField(
        verbose_name=_("percent"),
        max_digits=5,
        decimal_places=2,
        validators=[MinValueValidator(0),
                    MaxValueValidator(100)],
        blank=True,
        null=True,
    )

    progress = FloatField(
        verbose_name=_("progress"),
        validators=[MinValueValidator(0),
                    MaxValueValidator(100)],
        blank=True,
        null=True,
    )

    grade = IntegerField(
        verbose_name=_("grade"),
        validators=[MinValueValidator(-10),
                    MaxValueValidator(10)],
        blank=True,
        null=True,
    )

    slug = SlugField(
        unique=True,
        max_length=32,
        editable=True,
        db_index=True,
    )

    owner = EmailField(
        verbose_name=_("owner"),
        blank=True,
        null=True,
    )

    url = URLField(
        verbose_name=_("url"),
        blank=True,
        null=True,
    )

    key = UUIDField(default=uuid4, )

    description = TextField(verbose_name=_("description"), )

    active = BooleanField(verbose_name=_("active"), )

    highlight = NullBooleanField(verbose_name=_("highlight"), )

    creation_date = DateField(
        verbose_name=_("creation date"),
        auto_now_add=True,
    )

    last_modification_date = DateField(
        verbose_name=_("last modification date"),
        auto_now=True,
    )

    random_date = DateField(
        verbose_name=_("random date"),
        blank=True,
        null=True,
    )

    creation_datetime = DateTimeField(
        verbose_name=_("creation datetime"),
        auto_now_add=True,
    )

    last_modification_datetime = DateTimeField(
        verbose_name=_("last modification datetime"),
        auto_now=True,
    )

    random_datetime = DateTimeField(
        verbose_name=_("random datetime"),
        blank=True,
        null=True,
    )

    duration = DurationField(
        verbose_name=_("duration"),
        blank=True,
        null=True,
    )

    creation_time = TimeField(
        verbose_name=_("creation time"),
        auto_now_add=True,
    )

    last_modification_time = TimeField(
        verbose_name=_("last modification time"),
        auto_now=True,
    )

    random_time = TimeField(
        verbose_name=_("random time"),
        blank=True,
        null=True,
    )

    ip = GenericIPAddressField(
        verbose_name=_("IP v4 ou 6"),
        protocol="both",
        blank=True,
        null=True,
    )

    ipv4 = GenericIPAddressField(
        verbose_name=_("IP v4 as is"),
        protocol="IPv4",
        blank=True,
        null=True,
    )

    ipv6_forced = GenericIPAddressField(
        verbose_name=_("IP v6 (ipv4 will be converted)"),
        protocol="both",
        unpack_ipv4=True,
        blank=True,
        null=True,
    )

    ipv6 = GenericIPAddressField(
        verbose_name=_("IP v6"),
        protocol="IPv6",
        blank=True,
        null=True,
    )

    raw_data = BinaryField(
        verbose_name=_("raw data"),
        max_length=127,
        editable=True,
        blank=True,
        null=True,
    )

    def compute_upload_path(current_object, sub_path, filename):
        """Describe the image storage path"""
        today = now()
        return str(
            Path.joinpath(*list(
                map(
                    Path,
                    (
                        current_object._meta.app_label,  # pylint: disable=protected-access
                        current_object._meta.model_name,  # pylint: disable=protected-access
                        sub_path,
                        str(today.year),
                        str(today.month),
                        str(uuid4()) + Path(filename).suffix)))))

    file = FileField(
        verbose_name=_("file"),
        max_length=256,
        upload_to=partial(compute_upload_path, subpath="file"),
        null=True,
        blank=True,
    )

    image = ImageField(
        verbose_name=_("image"),
        max_length=256,
        upload_to=partial(compute_upload_path, subpath="image"),
        null=True,
        blank=True,
    )

    path = FilePathField(
        verbose_name=_("path"),
        path=settings.STATIC_PATH,
    )

    def __str__(self):
        """Return a string that represent the current object to an end user."""
        return self.label

    class Meta:  # pylint: disable=too-few-public-methods
        """Test Meta class"""

        verbose_name = _("test")
        verbose_name_plural = _("tests")
        ordering = ("number", )
示例#10
0
class Describes(models.Model) :
    title = models.CharField(max_length=100)
    description = models.TextField()
    technology = models.CharField(max_length=20)
    image = FilePathField(path='/img')
示例#11
0
 def test_path(self):
     path = os.path.dirname(__file__)
     field = FilePathField(path=path)
     self.assertEqual(field.path, path)
     self.assertEqual(field.formfield().path, path)