示例#1
0
 def test_deconstruct_args(self):
     field = ListCharField(models.CharField(max_length=5), max_length=32)
     name, path, args, kwargs = field.deconstruct()
     new = ListCharField(*args, **kwargs)
     self.assertEqual(
         new.base_field.max_length,
         field.base_field.max_length
     )
示例#2
0
    def test_max_length(self):
        field = ListCharField(models.CharField(max_length=32), size=3, max_length=32)

        field.clean({"a", "b", "c"}, None)

        with pytest.raises(exceptions.ValidationError) as excinfo:
            field.clean({"a", "b", "c", "d"}, None)
        assert excinfo.value.messages[0] == "List contains 4 items, it should contain no more than 3."
示例#3
0
 def test_field_checks(self):
     field = ListCharField(models.CharField(), max_length=32)
     field.set_attributes_from_name('field')
     errors = field.check()
     self.assertEqual(len(errors), 1)
     self.assertEqual(errors[0].id, 'django_mysql.E004')
     self.assertIn('Base field for list has errors', errors[0].msg)
     self.assertIn('max_length', errors[0].msg)
示例#4
0
 def test_max_length_including_base(self):
     field = ListCharField(
         models.CharField(max_length=32),
         size=2, max_length=32)
     field.set_attributes_from_name('field')
     errors = field.check()
     self.assertEqual(len(errors), 1)
     self.assertEqual(errors[0].id, 'django_mysql.E006')
     self.assertIn('Field can overrun', errors[0].msg)
示例#5
0
 def test_invalid_base_fields(self):
     field = ListCharField(
         models.ForeignKey('django_mysql_tests.Author'),
         max_length=32
     )
     field.set_attributes_from_name('field')
     errors = field.check()
     self.assertEqual(len(errors), 1)
     self.assertEqual(errors[0].id, 'django_mysql.E005')
     self.assertIn('Base field for list must be', errors[0].msg)
示例#6
0
    def test_max_length(self):
        field = ListCharField(
            models.CharField(max_length=32),
            size=3,
            max_length=32
        )

        field.clean({'a', 'b', 'c'}, None)

        with self.assertRaises(exceptions.ValidationError) as cm:
            field.clean({'a', 'b', 'c', 'd'}, None)
        self.assertEqual(
            cm.exception.messages[0],
            'List contains 4 items, it should contain no more than 3.'
        )
示例#7
0
class Company(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(null=True,
                            blank=True,
                            max_length=300,
                            verbose_name="nombre")
    link = models.URLField(null=True)
    reference = models.IntegerField(null=True,
                                    blank=True,
                                    verbose_name="nº de referencia")
    is_registered = models.BooleanField(null=True,
                                        blank=True,
                                        verbose_name="empresa colaboradora")
    description = models.TextField(null=True, verbose_name="descripción")
    resume = models.CharField(max_length=300,
                              null=True,
                              blank=True,
                              verbose_name="resumen")
    location_name = models.CharField(max_length=50, null=True)
    city = models.ForeignKey(City,
                             on_delete=models.CASCADE,
                             related_name='companies',
                             null=True,
                             blank=True,
                             verbose_name="ciudad")
    country = models.ForeignKey(Country,
                                on_delete=models.CASCADE,
                                related_name='companies',
                                null=True,
                                blank=True,
                                verbose_name="país")
    area = ListCharField(base_field=models.CharField(max_length=45),
                         size=34,
                         max_length=(1570),
                         null=True,
                         blank=True,
                         verbose_name="área")
    category = models.CharField(null=True,
                                blank=True,
                                max_length=100,
                                verbose_name="categoría")
    offers = models.IntegerField(null=True,
                                 blank=True,
                                 verbose_name="nº de ofertas")
    slug = models.CharField(max_length=300, null=True, blank=True)
    created_at = models.DateTimeField(
        editable=False,
        null=True,
        verbose_name="fecha de creción del registro"
    )  # models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(
        editable=False,
        null=True,
        verbose_name="fecha de actualización del registro"
    )  # models.DateTimeField(auto_now=True)
    history = HistoricalRecords()
    objects = CompanyManager()

    class Meta:
        verbose_name = "Compañía"  #"Company"
        verbose_name_plural = "Compañías"  #"Companies"
        ordering = ['name']

    def save(self, *args, **kwargs):
        if not self.id:
            self.created_at = timezone.localtime(timezone.now())
        self.updated_at = timezone.localtime(timezone.now())
        try:
            if self.name:
                self.slug = slugify(self.name)
            elif self.link:
                if self.link.endswith('/'):
                    slug = self.link.split('/')[-3]
                else:
                    slug = self.link.split('/')[-2]
                self.slug = slug
        except:
            pass
        super(Company, self).save(*args, **kwargs)
        if not self.slug:
            self.slug = str(self.id)
            super(Company, self).save(*args, **kwargs)

    def __str__(self):
        return self.name or ''

    def get_slug_from_link(self):
        link = self.link
        link = link[:-1] if self.link.endswith('/') else link
        try:
            slug = link.split('/')[-2]
        except Exception as e:
            slug = ''
        return slug
示例#8
0
 class InvalidListCharModel2(TemporaryModel):
     field = ListCharField(
         models.ForeignKey('testapp.Author', on_delete=models.CASCADE),
         max_length=32,
     )
 def test_model_field_formfield_size(self):
     model_field = ListCharField(models.IntegerField(), size=4)
     form_field = model_field.formfield()
     assert isinstance(form_field, SimpleListField)
     assert form_field.max_length == 4
示例#10
0
 def test_deconstruct_with_size(self):
     field = ListCharField(models.IntegerField(), size=3, max_length=32)
     name, path, args, kwargs = field.deconstruct()
     new = ListCharField(*args, **kwargs)
     assert new.size == field.size
示例#11
0
class IntListModel(Model):
    field = ListCharField(base_field=IntegerField(), size=5, max_length=32)
示例#12
0
class CharListDefaultModel(Model):
    field = ListCharField(base_field=CharField(max_length=5),
                          size=5,
                          max_length=32,
                          default=lambda: ["a", "d"])
示例#13
0
 def test_model_field_formfield_size(self):
     model_field = ListCharField(models.IntegerField(), size=4)
     form_field = model_field.formfield()
     self.assertIsInstance(form_field, SimpleListField)
     self.assertEqual(form_field.max_length, 4)
示例#14
0
class Hotels(models.Model):
    vendor_name = models.CharField(max_length=500 , blank=False)
    veg_price = models.FloatField()
    non_veg_price = models.FloatField()
    city = models.ForeignKey(City,on_delete=models.CASCADE)
    maximum = ListCharField(base_field = models.IntegerField() , max_length=10)
    minimum = ListCharField(base_field = models.IntegerField() , max_length=10)
    vendor_type = models.ManyToManyField(VendorType)
    address = models.CharField(max_length=500)
    phone = models.CharField(max_length=20)
    about = models.CharField(max_length=500)
    highlights = models.TextField()
    created_at = models.DateTimeField(auto_now=True)
    
    
    def __str__(self):
        return self.vendor_name
    
    
    def serialize(self,vendor_types):
        result = []
        for vendor in vendor_types:
            result.append(vendor.vendor_type)
        return result
    
    def is_valid_queryparam(param):
        return param != '' and param is not None
    

    # Method for searching and seralizeHotel
    def all_hotels(self, city , vegprice , nonvegprice , venue , capacity):
        results = {}
       
        hotels = Hotels.objects.all()
        
        if city:
            hotels = hotels.filter(city = City.objects.filter(city=city).first())
            
        if vegprice: 
            hotels = hotels.filter(veg_price__range=(0 , vegprice))
        
        if nonvegprice:
            hotels = hotels.filter(non_veg_price__range=(0 , nonvegprice))
        
        if venue:
            hotels = hotels.filter(vendor_type__vendor_type = venue)
                
        if capacity:
            hotels = hotels.filter(maximum__1__level__gte = capacity)
            
            
        
        for index in range(0, len(hotels)):
            results[index] = hotels[index].seralize_hotel()
        return results
            
    
    def seralize_hotel(self):
        return {
            'id' : self.id,
            'hotel' : self.vendor_name,
            'veg_price' : self.veg_price,
            'non_veg_price' : self.non_veg_price,
            'city' :  City.find_city(self.city),
            'maximum' : {
                'start' : self.maximum[0],
                 'end' : self.maximum[1],
            },
            'minimum': {
                'start' : self.minimum[0],
                'end'   : self.minimum[1]
            },
            'vendor_type' : self.serialize(list(self.vendor_type.all())) ,
            'phone' : self.phone,
            'highlights' : self.highlights,
            'about' : self.about,
            'address' : self.address,
            
        }
        
        
              
        
        


        
            
示例#15
0
class Skills(models.Model):

    id = models.CharField(max_length=250, primary_key=True)
    skills_set = ListCharField(base_field=CharField(max_length=10),
                               size=6,
                               max_length=(6 * 11))
示例#16
0
class ApplicationAccess(models.Model):
    """
    Specifies access control information for the associated Application.

    For usage details, see:
    - openedx/core/djangoapps/oauth_dispatch/docs/decisions/0007-include-organizations-in-tokens.rst

    .. no_pii:
    """

    # Content org filters are of the form "content_org:<org_name>" eg. "content_org:SchoolX"
    # and indicate that for anything that cares about the content_org filter, that the response
    # should be filtered based on the filter value.  ie. We should only get responses pertain
    # to objects that are relevant to the SchoolX organization.
    CONTENT_ORG_FILTER_NAME = 'content_org'

    application = models.OneToOneField(oauth2_settings.APPLICATION_MODEL, related_name='access',
                                       on_delete=models.CASCADE)
    scopes = ListCharField(
        base_field=models.CharField(max_length=32),
        size=25,
        max_length=(25 * 33),  # 25 * 32 character scopes, plus commas
        help_text=_('Comma-separated list of scopes that this application will be allowed to request.'),
    )

    filters = ListCharField(
        base_field=models.CharField(max_length=32),
        size=25,
        max_length=(25 * 33),  # 25 * 32 character filters, plus commas
        help_text=_('Comma-separated list of filters that this application will be allowed to request.'),
        null=True,
        blank=True,
    )

    class Meta:
        app_label = 'oauth_dispatch'

    @classmethod
    def get_scopes(cls, application):
        return cls.objects.get(application=application).scopes

    @classmethod
    def get_filters(cls, application):
        return cls.objects.get(application=application).filters

    @classmethod
    def get_filter_values(cls, application, filter_name):  # lint-amnesty, pylint: disable=missing-function-docstring
        filters = cls.get_filters(application=application)
        if filters:
            for filter_constraint in filters:
                name, filter_value = filter_constraint.split(':', 1)
                if name == filter_name:
                    yield filter_value

    def __str__(self):
        """
        Return a unicode representation of this object.
        """
        return "{application_name}:{scopes}:{filters}".format(
            application_name=self.application.name,
            scopes=self.scopes,
            filters=self.filters,
        )
示例#17
0
class Config(models.Model):
    environment = ListCharField(base_field=models.CharField(max_length=100),
                                max_length=(10 * 100))
    random_seed = ListCharField(base_field=models.IntegerField(),
                                max_length=(10 * 100))
    number_generations = ListCharField(base_field=models.IntegerField(),
                                       max_length=(10 * 100))
    use_worker_processes = models.BooleanField()

    optimizer_type = ListCharField(base_field=models.CharField(max_length=100),
                                   max_length=(10 * 100))
    optimizer_population_size = ListCharField(base_field=models.IntegerField(),
                                              max_length=(10 * 100))
    optimizer_sigma = ListCharField(
        base_field=models.CharField(max_length=100),
        max_length=(10 * 100))  #decimal
    optimizer_checkpoint_frequency = ListCharField(
        base_field=models.IntegerField(), max_length=(10 * 100))
    optimizer_hof_size = ListCharField(base_field=models.IntegerField(),
                                       max_length=(10 * 100))

    brain_type = ListCharField(base_field=models.CharField(max_length=100),
                               max_length=(10 * 100))
    brain_number_neurons = ListCharField(base_field=models.IntegerField(),
                                         max_length=(10 * 100))
    brain_use_bias = models.BooleanField()
    brain_delta_t = ListCharField(base_field=models.CharField(max_length=100),
                                  max_length=(10 * 100))  #decimal
    brain_neuron_activation = ListCharField(
        base_field=models.CharField(max_length=100), max_length=(10 * 100))
    brain_neuron_activation_inplace = models.BooleanField()
    brain_normalize_input = models.BooleanField()
    brain_normalize_input_target = ListCharField(
        base_field=models.IntegerField(), max_length=(10 * 100))
    brain_optimize_state_boundaries = ListCharField(
        base_field=models.CharField(max_length=100), max_length=(10 * 100))
    brain_clipping_range_max = ListCharField(
        base_field=models.CharField(max_length=100),
        max_length=(10 * 100))  #decimal
    brain_clipping_range_min = ListCharField(
        base_field=models.CharField(max_length=100),
        max_length=(10 * 100))  #decimal
    brain_optimize_y0 = models.BooleanField()
    brain_set_principle_diagonal_elements_of_W_negative = models.BooleanField()
    brain_w_mask = ListCharField(base_field=models.CharField(max_length=100),
                                 max_length=(10 * 100))
    brain_w_mask_param = ListCharField(base_field=models.IntegerField(),
                                       max_length=(10 * 100))
    brain_v_mask = ListCharField(base_field=models.CharField(max_length=100),
                                 max_length=(10 * 100))
    brain_v_mask_param = ListCharField(base_field=models.IntegerField(),
                                       max_length=(10 * 100))
    brain_t_mask = ListCharField(base_field=models.CharField(max_length=100),
                                 max_length=(10 * 100))
    brain_t_mask_param = ListCharField(base_field=models.IntegerField(),
                                       max_length=(10 * 100))
    brain_parameter_perturbations = ListCharField(
        base_field=models.CharField(max_length=100),
        max_length=(10 * 100))  #decimal

    episode_runner_type = ListCharField(
        base_field=models.CharField(max_length=100), max_length=(10 * 100))
    episode_runner_keep_env_seed_fixed_during_generation = models.BooleanField(
    )
    episode_runner_number_fitness_runs = ListCharField(
        base_field=models.IntegerField(), max_length=(10 * 100))
    episode_runner_reuse_env = models.BooleanField()
    episode_runner_max_steps_per_run = ListCharField(
        base_field=models.IntegerField(), max_length=(10 * 100))
    episode_runner_max_steps_penalty = ListCharField(
        base_field=models.IntegerField(), max_length=(10 * 100))
示例#18
0
class Graph(models.Model):
    name = models.CharField(max_length=100, primary_key=True)
    adj_list = ListCharField(base_field=models.CharField(max_length=100),
                             size=1000,
                             max_length=1000 * 101)
示例#19
0
class Busstop(models.Model):
    name = models.CharField(max_length=100, primary_key=True)
    bus_visit = ListCharField(base_field=models.CharField(max_length=100),
                              size=1000,
                              max_length=1000 * 101)
示例#20
0
class Job(models.Model):

    STATE_CREATED = 'Nueva'
    STATE_WITHOUT_CHANGES = ''
    STATE_UPDATED = 'Actualizada'
    STATE_CLOSED = 'Inscripción cerrada'
    STATE_CHOICES = ((STATE_CREATED, 'Nueva'), (STATE_WITHOUT_CHANGES,
                                                'Sin cambios'),
                     (STATE_UPDATED, 'Actualizada'), (STATE_CLOSED,
                                                      'Inscripción cerrada'))
    TYPE_INTERNATIONAL = 'ofertas-internacionales'
    TYPE_NATIONAL = 'trabajo'
    TYPE_FIRST_JOB = 'primer-empleo'
    TYPE_CHOICES = (
        (TYPE_INTERNATIONAL, 'Empleo internacional'),
        (TYPE_NATIONAL, 'Empleo nacional'),
        (TYPE_FIRST_JOB, 'Primer empleo'),
    )

    CONTRACT_FIXED_DURATION = 'Contrato De duración determinada'
    CONTRACT_UNSPECIFIED = 'Contrato sin especificar'
    CONTRACT_PRACTICES = 'Contrato Prácticas'
    CONTRACT_UNDEFINED = 'Contrato Indefinido'
    CONTRACT_FREELANCE = 'Contrato Autónomo o freelance'
    CONTRACT_FIXED_DISCONTINUOUS = 'Contrato Fijo discontinuo'
    CONTRACT_FORMATIVE = "Contrato Formativo"
    CONTRACT_CHOICES = (
        (CONTRACT_UNSPECIFIED, 'sin especificar'),
        (CONTRACT_PRACTICES, 'prácticas'),
        (CONTRACT_UNDEFINED, 'indefinido'),
        (CONTRACT_FREELANCE, 'autónomo o freelance'),
        (CONTRACT_FIXED_DISCONTINUOUS, 'fijo discontinuo'),
        (CONTRACT_FORMATIVE, "formativo"),
        (CONTRACT_FIXED_DURATION, 'de duración determinada'),
    )

    WORKING_DAY_TELE = "Jornada Tele Trabajo"
    WORKING_DAY_UNSPECIFIED = "Jornada sin especificar"
    WORKING_DAY_INTENSIVE = "Jornada Intensiva"
    WORKING_DAY_INDIFFERENT = "Jornada Indiferente"
    WORKING_DAY_PARTIAL = "Jornada Parcial"
    WORKING_DAY_WEEKEND = "Jornada Fin de Semana"
    WORKING_DAY_COMPLETE = "Jornada Completa"
    WORKING_DAY_CHOICES = (
        (WORKING_DAY_UNSPECIFIED, "sin especificar"),
        (WORKING_DAY_INTENSIVE, "intensiva"),
        (WORKING_DAY_INDIFFERENT, "flexible"),
        (WORKING_DAY_PARTIAL, "parcial"),
        (WORKING_DAY_WEEKEND, "fin de semana"),
        (WORKING_DAY_COMPLETE, "completa"),
        (WORKING_DAY_TELE, "tele trabajo"),
    )

    CATEGORY_KNOBS = "Mandos"
    CATEGORY_EMPLOYEES = "Empleados"
    CATEGORY_TECHNICIANS = "Técnicos"
    CATEGORY_DIRECTION = "Dirección"
    CATEGORY_UNSPECIFIED = "Sin especificar"

    CATEGORY_CHOICES = (
        (CATEGORY_KNOBS, "Mandos"),
        (CATEGORY_EMPLOYEES, "Empleados"),
        (CATEGORY_TECHNICIANS, "Técnicos"),
        (CATEGORY_DIRECTION, "Dirección"),
        (CATEGORY_UNSPECIFIED, "Sin especificar"),
    )

    # 20 areas
    AREA_EDUCATION_TRAINING = "Educación, formación"
    AREA_TECHNOLOGY_AND_INFORMATICS = "Tecnología e informática"
    AREA_HEALTH_HEALTH_AND_SOCIAL_SERVICES = "Sanidad, salud y servicios sociales"
    AREA_MEDIA_PUBLISHING_AND_GRAPHIC_ARTS = "Medios, editorial y artes gráficas"
    AREA_SHOPPING_LOGISTICS_AND_TRANSPORTATION = "Compras, logística y transporte"
    AREA_ADMINISTRATIVE_AND_SECRETARIAT = "Administrativos y secretariado"
    AREA_PROFESSIONALS_ARTS_AND_CRAFTS = "Profesionales, artes y oficios"
    AREA_TELECOMMUNICATIONS = "Telecomunicaciones"
    AREA_LEGAL = "Legal"
    AREA_INTERNET = "Internet"
    AREA_BANKING_AND_INSURANCE = "Banca y seguros"
    AREA_QUALITY_ID_PRL_AND_ENVIRONMENT = "Calidad, I+D, PRL y medio ambiente"
    AREA_HUMAN_RESOURCES = "Recursos humanos"
    AREA_SALES_MANAGER = "Comercial, ventas"
    AREA_ENGINEERING_AND_PRODUCTION = "Ingeniería y producción"
    AREA_CUSTOMER_SUPPORT = "Atención al cliente"
    AREA_CONSTRUCTION_AND_REAL_ESTATE = "Construcción e inmobiliaria"
    AREA_HOSTELRY_TOURISM = "Hostelería, Turismo"
    AREA_BUSINESS_ADMINISTRATION = "Administración de Empresas"
    AREA_MARKETING_AND_COMMUNICATION = "Marketing y comunicación"
    AREA_CHOICES = (
        (AREA_EDUCATION_TRAINING, "Educación, formación"),
        (AREA_TECHNOLOGY_AND_INFORMATICS, "Tecnología e informática"),
        (AREA_HEALTH_HEALTH_AND_SOCIAL_SERVICES,
         "Sanidad, salud y servicios sociales"),
        (AREA_MEDIA_PUBLISHING_AND_GRAPHIC_ARTS,
         "Medios, editorial y artes gráficas"),
        (AREA_SHOPPING_LOGISTICS_AND_TRANSPORTATION,
         "Compras, logística y transporte"),
        (AREA_ADMINISTRATIVE_AND_SECRETARIAT,
         "Administrativos y secretariado"),
        (AREA_PROFESSIONALS_ARTS_AND_CRAFTS, "Profesionales, artes y oficios"),
        (AREA_TELECOMMUNICATIONS, "Telecomunicaciones"),
        (AREA_LEGAL, "Legal"),
        (AREA_INTERNET, "Internet"),
        (AREA_BANKING_AND_INSURANCE, "Banca y seguros"),
        (AREA_QUALITY_ID_PRL_AND_ENVIRONMENT,
         "Calidad, I+D, PRL y medio ambiente"),
        (AREA_HUMAN_RESOURCES, "Recursos humanos"),
        (AREA_SALES_MANAGER, "Comercial, ventas"),
        (AREA_ENGINEERING_AND_PRODUCTION, "Ingeniería y producción"),
        (AREA_CUSTOMER_SUPPORT, "Atención al cliente"),
        (AREA_CONSTRUCTION_AND_REAL_ESTATE, "Construcción e inmobiliaria"),
        (AREA_HOSTELRY_TOURISM, "Hostelería, Turismo"),
        (AREA_BUSINESS_ADMINISTRATION, "Administración de Empresas"),
        (AREA_MARKETING_AND_COMMUNICATION, "Marketing y comunicación"),
    )
    id = models.IntegerField(unique=True, primary_key=True)
    name = models.CharField(max_length=200, verbose_name="nombre")
    link = models.URLField(null=True)

    state = models.CharField(max_length=30,
                             choices=STATE_CHOICES,
                             null=True,
                             blank=True,
                             verbose_name="estado")

    type = models.CharField(
        max_length=30,
        choices=TYPE_CHOICES,
        default=TYPE_NATIONAL,
        verbose_name="tipo",
    )
    _summary = ListCharField(base_field=models.CharField(max_length=100),
                             size=6,
                             max_length=(6 * 101),
                             null=True)
    _experience = models.CharField(max_length=40, null=True, blank=True)
    _salary = models.CharField(max_length=40, null=True, blank=True)
    _contract = models.CharField(max_length=40, null=True, blank=True)
    _working_day = models.CharField(max_length=40, null=True, blank=True)
    minimum_years_of_experience = models.PositiveIntegerField(
        null=True, blank=True, default=0, verbose_name="experiencia mínima")
    recommendable_years_of_experience = models.PositiveIntegerField(
        null=True,
        blank=True,
        default=0,
        verbose_name="experiencia recomendable")
    minimum_salary = models.PositiveIntegerField(
        null=True, blank=True, verbose_name="salario míminimo")
    maximum_salary = models.PositiveIntegerField(null=True,
                                                 blank=True,
                                                 verbose_name="salario máximo")
    working_day = models.CharField(
        max_length=30,
        choices=WORKING_DAY_CHOICES,
        default=CATEGORY_UNSPECIFIED,
        verbose_name="jornada laboral",
    )
    contract = models.CharField(
        max_length=40,
        choices=CONTRACT_CHOICES,
        default=CONTRACT_UNSPECIFIED,
        verbose_name="tipo de contrato",
    )

    cities = models.ManyToManyField(
        City,
        related_name='jobs',
        null=True,
        blank=True,
        verbose_name="ciudades",
    )
    province = models.ForeignKey(
        Province,
        on_delete=models.CASCADE,
        related_name='jobs',
        null=True,
        blank=True,
        verbose_name="provincia",
    )
    country = models.ForeignKey(
        Country,
        on_delete=models.CASCADE,
        related_name='jobs',
        null=True,
        blank=True,
        verbose_name="país",
    )
    languages = models.ManyToManyField(
        Language,
        related_name='jobs',
        null=True,
        blank=True,
        verbose_name="idiomas",
    )
    _cities = ListCharField(base_field=models.CharField(max_length=100),
                            size=6,
                            max_length=(6 * 101),
                            null=True,
                            blank=True)
    _province = models.CharField(null=True, max_length=100,
                                 blank=True)  # Model
    _country = models.CharField(null=True, max_length=30)  #Model
    nationality = models.CharField(max_length=30, verbose_name="nacionalidad")
    first_publication_date = models.DateField(
        null=True,
        blank=True,
        default=None,
        verbose_name="fecha de publicación de la oferta")
    last_update_date = models.DateField(
        null=True,
        blank=True,
        default=None,
        verbose_name="fecha de actualización de la oferta")
    expiration_date = models.DateField(
        null=True,
        blank=True,
        default=None,
        verbose_name="fecha de caducidad de la oferta"
    )  # models.DateTimeField(auto_now_add=True)
    description = models.TextField(null=True,
                                   blank=True,
                                   verbose_name="descripción")
    functions = models.TextField(null=True,
                                 blank=True,
                                 verbose_name="funciones")
    requirements = models.TextField(null=True,
                                    blank=True,
                                    verbose_name="requisitos")
    it_is_offered = models.TextField(
        null=True, blank=True, verbose_name="se ofrece")  #NULL constraint
    tags = models.TextField(null=True, blank=True,
                            verbose_name="etiquetas")  #Model
    area = models.CharField(max_length=40,
                            choices=AREA_CHOICES,
                            verbose_name="área")
    category_level = models.CharField(
        max_length=20,
        choices=CATEGORY_CHOICES,
        default=CATEGORY_UNSPECIFIED,
        null=True,
        verbose_name="categoría o nivel",
    )
    vacancies = models.PositiveIntegerField(null=True,
                                            blank=True,
                                            verbose_name="nº de vacantes")
    registered_people = models.PositiveIntegerField(default=0,
                                                    verbose_name="inscritos")
    vacancies_update = models.PositiveIntegerField(null=True, blank=True)
    company = models.ForeignKey(Company,
                                null=True,
                                default=None,
                                on_delete=models.CASCADE,
                                related_name='jobs',
                                verbose_name="compañía")
    created_at = models.DateTimeField(
        editable=False,
        null=True,
        verbose_name="fecha de creación del registro"
    )  # models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(
        editable=False,
        null=True,
        blank=True,
        verbose_name="fecha de actualización del registro"
    )  # models.DateTimeField(auto_now=True)
    history = HistoricalRecords()
    objects = JobManager()

    class Meta:
        verbose_name = "Oferta de empleo"
        verbose_name_plural = "Ofertas de empleo"
        ordering = ['-created_at', 'name']
        #unique_together = (('id'),)

    def __str__(self):
        city = ""
        try:
            city = " - %s" % (self.cities.all().first())
        except:
            pass
        return "%s - %s%s" % (self.name, self.type, city)

    def save(self, *args, **kwargs):
        if not self.id:
            self.created_at = timezone.localtime(timezone.now())
        self.updated_at = timezone.localtime(timezone.now())
        try:
            super(Job, self).save(*args, **kwargs)
        except InterfaceError as ie:
            db.connection.close()
            super(Job, self).save(*args, **kwargs)

    def get_absolute_url(self):
        return reverse('detail', args=[str(self.pk)])

    def company_link_(self):
        return self.company.link

    def fields(self):
        return [field['name'] for field in self._meta.fields]

    def display_cities(self):
        """
        For display the cities and the country of an offer in the admin section
        :return: The cities and the country
        """
        cities = self.cities.all()[0:3]
        if cities:
            names = [city.name for city in cities]
            return f'{", ".join(names)} ({cities[0].country.name})'
        else:
            return None

    display_cities.short_description = 'Cities (Country)'

    @classmethod
    def add_city(cls, job, city):
        try:
            job_ = cls.objects.get(id=job.id)
            job_.cities.add(city)
        except Exception as e:
            pass
示例#21
0
 def test_model_field_formfield_size(self):
     model_field = ListCharField(models.IntegerField(), size=4)
     form_field = model_field.formfield()
     assert isinstance(form_field, SimpleListField)
     assert form_field.max_length == 4
示例#22
0
class Orders(models.Model):
    customer_name = models.CharField(max_length=20)
    order_items = ListCharField()
 class InvalidListCharModel(TemporaryModel):
     field = ListCharField(
         models.ForeignKey('testapp.Author'),
         max_length=32
     )
示例#24
0
class OnsenInn(VoteModel, models.Model):

    inn_id = models.IntegerField()
    inn_name = models.CharField(max_length=100)
    inn_photo = models.ImageField(upload_to='images/',
                                  default='images/default.jpg',
                                  blank=True,
                                  null=True)

    #extra data
    inn_photo_2 = models.ImageField(upload_to='images/',
                                    default='images/default.jpg',
                                    blank=True,
                                    null=True)
    inn_photo_3 = models.ImageField(upload_to='images/',
                                    default='images/default.jpg',
                                    blank=True,
                                    null=True)
    inn_photo_4 = models.ImageField(upload_to='images/',
                                    default='images/default.jpg',
                                    blank=True,
                                    null=True)
    inn_headline = models.CharField(blank=True, null=True, max_length=300)
    inn_overview = models.TextField(blank=True, null=True)

    inn_min_price = models.IntegerField()
    review_room = models.DecimalField(blank=True,
                                      null=True,
                                      max_digits=2,
                                      decimal_places=1)
    review_bath = models.DecimalField(blank=True,
                                      null=True,
                                      max_digits=2,
                                      decimal_places=1)
    review_breakfast = models.DecimalField(blank=True,
                                           null=True,
                                           max_digits=2,
                                           decimal_places=1)
    review_dinner = models.DecimalField(blank=True,
                                        null=True,
                                        max_digits=2,
                                        decimal_places=1)
    review_service = models.DecimalField(blank=True,
                                         null=True,
                                         max_digits=2,
                                         decimal_places=1)
    review_cleaness = models.DecimalField(blank=True,
                                          null=True,
                                          max_digits=2,
                                          decimal_places=1)
    rooms_total = models.IntegerField(blank=True, null=True)
    baths_total = models.IntegerField(blank=True, null=True)

    service_leisure = ListCharField(base_field=models.CharField(max_length=20),
                                    size=30,
                                    max_length=(30 * 21),
                                    blank=True,
                                    null=True)

    free_wifi = models.BooleanField(blank=True, null=True)
    convenience_store = models.BooleanField(blank=True, null=True)

    hand_towel = models.BooleanField(blank=True, null=True)
    body_wash = models.BooleanField(blank=True, null=True)
    hairdryer = models.BooleanField(blank=True, null=True)
    onsui_toilet = models.BooleanField(blank=True, null=True)

    dental_amenities = models.BooleanField(blank=True, null=True)
    bar_soap = models.BooleanField(blank=True, null=True)
    duvet = models.BooleanField(blank=True, null=True)
    hair_brush = models.BooleanField(blank=True, null=True)

    bath_towel = models.BooleanField(blank=True, null=True)
    yukata = models.BooleanField(blank=True, null=True)
    razor = models.BooleanField(blank=True, null=True)

    #separate_toilet = models.BooleanField(blank=True, null=True)
    shampoo = models.BooleanField(blank=True, null=True)
    pajamas = models.BooleanField(blank=True, null=True)
    shower_cap = models.BooleanField(blank=True, null=True)

    conditioner = models.BooleanField(blank=True, null=True)
    bathrobe = models.BooleanField(blank=True, null=True)
    cotton_swab = models.BooleanField(blank=True, null=True)

    category = models.IntegerField(blank=True, null=True)
    onsen = models.ForeignKey(Onsen, on_delete=models.CASCADE)

    #votes = VotableManager()

    def __str__(self):
        return self.inn_name
示例#25
0
class Training(models.Model):
    index = models.IntegerField()
    data = ListCharField(base_field=models.IntegerField(),
                         size=800,
                         max_length=11 * 800)
示例#26
0
class CharListModel(Model):
    field = ListCharField(
        base_field=CharField(max_length=8),
        size=3,
        max_length=32,
    )
示例#27
0
class Artist(models.Model):
    def image_upload_path(self, filename):
        extension = filename.rsplit('.', 1)[-1]
        return f'backend/uploads/artists/profiles/{timezone.now().isoformat()}.{extension}'

    id = models.AutoField(primary_key=True)
    user = models.ForeignKey(User,
                             related_name='artist',
                             on_delete=models.CASCADE)
    description = models.TextField(null=True)
    profile = models.ImageField(null=True,
                                blank=True,
                                upload_to=image_upload_path)
    color = models.CharField(max_length=20, null=True)

    collaboration_types = ListCharField(
        base_field=models.CharField(choices=FIELDS, max_length=20),
        max_length=(20 * 7),
        null=True,
    )
    creation_type = models.CharField(choices=FIELDS, max_length=20)

    @property
    def name(self):
        return self.user.name

    @property
    def waiting_collabos(self):
        return Collabo.objects.filter(main_artist=self,
                                      status=Collabo.STATUS_WAITING)

    @property
    def working_collabos(self):
        return Collabo.objects.filter(
            Q(main_artist=self)
            | Q(sub_artist=self)).filter(status=Collabo.STATUS_WORKING)

    @property
    def completed_collabos(self):
        return Collabo.objects.filter(
            Q(main_artist=self)
            | Q(sub_artist=self)).filter(status=Collabo.STATUS_COMPLETED)

    @property
    def favorite_artists(self):
        favorite_artists = FavoriteArtist.objects.filter(who=self).values_list(
            'favorite', flat=True)
        return Artist.objects.filter(id__in=favorite_artists)

    @property
    def favorite_collabos(self):
        favorite_collabos = FavoriteCollabo.objects.filter(
            who=self).values_list('favorite', flat=True)
        return Collabo.objects.filter(id__in=favorite_collabos)

    @property
    def followers(self):
        followers = FavoriteArtist.objects.filter(favorite=self).values_list(
            'who', flat=True)
        return Artist.objects.filter(id__in=followers)

    @property
    def arts(self):
        return Art.objects.filter(artist=self)
示例#28
0
 def test_deconstruct(self):
     field = ListCharField(models.IntegerField(), max_length=32)
     name, path, args, kwargs = field.deconstruct()
     new = ListCharField(*args, **kwargs)
     assert new.base_field.__class__ == field.base_field.__class__
示例#29
0
 def test_deconstruct(self):
     field = ListCharField(models.IntegerField(), max_length=32)
     name, path, args, kwargs = field.deconstruct()
     new = ListCharField(*args, **kwargs)
     assert new.base_field.__class__ == field.base_field.__class__
示例#30
0
 def test_model_field_formfield(self):
     model_field = ListCharField(models.CharField(max_length=27))
     form_field = model_field.formfield()
     assert isinstance(form_field, SimpleListField)
     assert isinstance(form_field.base_field, forms.CharField)
     assert form_field.base_field.max_length == 27
示例#31
0
 def test_deconstruct_args(self):
     field = ListCharField(models.CharField(max_length=5), max_length=32)
     name, path, args, kwargs = field.deconstruct()
     new = ListCharField(*args, **kwargs)
     assert new.base_field.max_length == field.base_field.max_length
示例#32
0
 class InvalidListCharModel1(TemporaryModel):
     field = ListCharField(models.CharField(), max_length=32)
示例#33
0
 def test_int(self):
     field = ListCharField(models.IntegerField(), max_length=32)
     assert field.description == "List of Integer"
示例#34
0
 class InvalidListCharModel4(TemporaryModel):
     field = ListCharField(
         models.CharField(max_length=2),
         size=2,
     )
示例#35
0
class Photos(models.Model):
    name_reference = models.CharField(max_length=100)
    list_photos_profile = ListCharField(base_field=CharField(max_length=200),
                                        size=600,
                                        max_length=600 * 1100)
示例#36
0
 def test_deconstruct_with_size(self):
     field = ListCharField(models.IntegerField(), size=3, max_length=32)
     name, path, args, kwargs = field.deconstruct()
     new = ListCharField(*args, **kwargs)
     assert new.size == field.size
示例#37
0
 def test_deconstruct(self):
     field = ListCharField(models.IntegerField(), max_length=32)
     name, path, args, kwargs = field.deconstruct()
     new = ListCharField(*args, **kwargs)
     self.assertEqual(type(new.base_field), type(field.base_field))
示例#38
0
 def test_char(self):
     field = ListCharField(models.CharField(max_length=5), max_length=32)
     assert field.description == "List of String (up to %(max_length)s)"
示例#39
0
 class Invalid(models.Model):
     field = ListCharField(
         models.ForeignKey("testapp.Author", on_delete=models.CASCADE),
         max_length=32,
     )
示例#40
0
 def test_model_field_formfield(self):
     model_field = ListCharField(models.CharField(max_length=27))
     form_field = model_field.formfield()
     assert isinstance(form_field, SimpleListField)
     assert isinstance(form_field.base_field, forms.CharField)
     assert form_field.base_field.max_length == 27
示例#41
0
 def test_model_field_formfield(self):
     model_field = ListCharField(models.CharField(max_length=27))
     form_field = model_field.formfield()
     self.assertIsInstance(form_field, SimpleListField)
     self.assertIsInstance(form_field.base_field, forms.CharField)
     self.assertEqual(form_field.base_field.max_length, 27)
示例#42
0
class ProviderFilter(StackedConfigurationModel):
    """
    Associate allow/deny-lists of discussions providers with courses/orgs
    """

    allow = ListCharField(
        base_field=models.CharField(
            choices=[(provider, provider)
                     for provider in get_supported_providers()],
            max_length=20,
        ),
        blank=True,
        help_text=_("Comma-separated list of providers to allow, eg: {choices}"
                    ).format(choices=','.join(get_supported_providers()), ),
        # max_length = (size * (max_length + len(','))
        # max_length = (   3 * (        20 +       1))
        max_length=63,
        # size = len(get_supported_providers())
        size=3,
        verbose_name=_('Allow List'),
    )
    deny = ListCharField(
        base_field=models.CharField(
            choices=[(provider, provider)
                     for provider in get_supported_providers()],
            max_length=20,
        ),
        blank=True,
        help_text=_(
            "Comma-separated list of providers to deny, eg: {choices}").format(
                choices=','.join(get_supported_providers()), ),
        # max_length = (size * (max_length + len(','))
        # max_length = (   3 * (        20 +       1))
        max_length=63,
        # size = len(get_supported_providers())
        size=3,
        verbose_name=_('Deny List'),
    )

    STACKABLE_FIELDS = (
        'enabled',
        'allow',
        'deny',
    )

    def __str__(self):
        return 'ProviderFilter(org="{org}", course="{course}", allow={allow}, deny={deny})'.format(
            allow=self.allow,
            course=self.course or '',
            deny=self.deny,
            org=self.org or '',
        )

    @property
    def available_providers(self) -> list[str]:
        """
        Return a filtered list of available providers
        """
        _providers = get_supported_providers()
        if self.allow:
            _providers = [
                provider for provider in _providers if provider in self.allow
            ]
        if self.deny:
            _providers = [
                provider for provider in _providers
                if provider not in self.deny
            ]
        return _providers

    @classmethod
    def get_available_providers(cls, course_key: CourseKey) -> list[str]:
        _filter = cls.current(course_key=course_key)
        providers = _filter.available_providers
        return providers
示例#43
0
 class Invalid(models.Model):
     field = ListCharField(models.CharField(max_length=2), size=2)