Beispiel #1
0
class Report(models.Model):
    candidate = models.ForeignKey(User, on_delete=models.CASCADE)
    requirements = SeparatedValuesField(null=True, max_length=150, token=',')
    keycompitency = SeparatedValuesField(null=True, max_length=150, token=',')
    grading = SeparatedValuesField(null=True, max_length=150, token=',')
    score = models.IntegerField(null=True)
    github = models.CharField(null=True, max_length=300)
Beispiel #2
0
class Report(ModelBase, AccessRestrictedModel):
    """
    Model for storing reports
    """

    class Meta:
        permissions = (
            ('run_report', 'Can run report'),
            ('download_data', 'Can download data'),
            ('download_member_data', 'Can download member data'),
            ('download_division_data', 'Can download division data'),
            ('download_subscription_data', 'Can download subscription data'),
            ('download_account_data', 'Can download account data'),
            ('download_costcenter_data', 'Can download costcenter data'),
            ('download_costobject_data', 'Can download costobject data'),
            ('download_transaction_data', 'Can download transaction data'),
            ('download_closuretransaction_data', 'Can download closuretransaction data'),
            ('download_closurebalance_data', 'Can download closurebalance data'),
        )

    MEMBER = 'MEM'
    DIVISION = 'DIV'
    SUBSCRIPTION = 'SUB'
    ACCOUNT = 'ACC'
    COSTCENTER = 'COC'
    COSTOBJECT = 'COO'
    TRANSACTION = 'TRA'
    CLOSURETRANSACTION = 'CTR'
    CLOSUREBALANCE = 'CBA'

    MODELS = (
        (MEMBER, _('Member')),
        (DIVISION, _('Division')),
        (SUBSCRIPTION, _('Subscription')),
        (ACCOUNT, _('Account')),
        (COSTCENTER, _('Costcenter')),
        (COSTOBJECT, _('Costobject')),
        (TRANSACTION, _('Transaction')),
        (CLOSURETRANSACTION, _('Closuretransaction')),
        (CLOSUREBALANCE, _('Closurebalance'))
    )

    name = models.CharField(null=False, blank=False, max_length=255)
    
    description = models.TextField(null=True, blank=True)

    report = models.FileField(null=True, blank=True, upload_to=get_report_path)

    model = SeparatedValuesField(null=False, blank=False, max_length=255, choices=MODELS, default=[MEMBER])

    jsonql_query = models.TextField(null=False, blank=False)

    uuid = models.UUIDField(default=uuid.uuid4, editable=False)

    resources = models.CharField(blank=True, null=True, max_length=255)
        
    def clean(self, *args, **kwargs):
        super(Report, self).clean(*args, **kwargs)
        if not self.report:
            raise ValidationError(_('Report must not be empty'))
class GroupOfReports(models.Model):
    name = models.CharField('Наименование группы', max_length=200)
    organisations = SeparatedValuesField('Список субъектов',
                                         max_length=10000,
                                         null=True)

    def __str__(self):
        return self.name
Beispiel #4
0
class part(models.Model):
    name = models.CharField(max_length=254, default='')
    url = models.CharField(max_length=254, default='')
    category = models.CharField(max_length=254, default='')
    image = models.ImageField(upload_to='media/images', max_length=None)
    description = models.TextField()
    price = models.DecimalField(max_digits=9, decimal_places=2, null=True)
    rating = models.IntegerField(blank=False, default=1)
    specs_categorys = SeparatedValuesField(max_length=512,
                                           token=',',
                                           null=True)
    specs_values = SeparatedValuesField(max_length=512, token=',', null=True)
    available_amount = models.CharField(max_length=15, default='')
    available_from = models.DateField(blank=True, null=True)
    countsold = models.IntegerField(blank=False, default=1)

    def __str__(self):
        return self.name
Beispiel #5
0
class Cartoon(models.Model):
    def __str__(self):
        return self.name

    name = models.TextField(unique=True)
    image = models.TextField()
    urls = SeparatedValuesField(token=',')

    objects = CartoonManager()
class Report(models.Model):
    status_choice = (('Сформирован', 'Сформирован'), ('Рассматривается',
                                                      'Рассматривается'),
                     ('Доработать', 'Доработать'), ('Новый', 'Новый'))
    name = models.CharField('Наименование отчёта', max_length=300)
    start_date = models.DateTimeField('Дата и время создания',
                                      auto_now_add=True)
    update_time = models.DateTimeField('Время последнего обновления',
                                       auto_now=True,
                                       null=True)
    organisation = models.ForeignKey(Organisation,
                                     default=None,
                                     null=True,
                                     on_delete=models.DO_NOTHING)
    status = models.CharField('Статус', max_length=20, choices=status_choice)
    count_col = models.IntegerField('Кол-во колонок', default='')
    count_row = models.IntegerField('Кол-во строк', default='')
    context = SeparatedValuesField('Содержание таблицы',
                                   max_length=10000,
                                   null=True)
    top_names = SeparatedValuesField('Имена заголовков таблицы',
                                     max_length=1000,
                                     null=True,
                                     blank=True)
    message = models.TextField('Приложенное сообщение',
                               max_length=3000,
                               default='')
    message_help = models.TextField('Сообщение для помощи',
                                    max_length=1000,
                                    default='',
                                    blank=True)
    typeOne = models.BooleanField('Одинарное значение?', default=True)
    string_informations = models.TextField('Информация по строкам',
                                           max_length=5000,
                                           default='')
    group = models.ForeignKey(GroupOfReports,
                              default=None,
                              on_delete=models.CASCADE)

    def __str__(self):
        return self.name

    class Meta:
        ordering = ['-start_date']
Beispiel #7
0
class Bible(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    book = models.CharField(max_length=50)
    chapter = models.PositiveSmallIntegerField()
    verses = SeparatedValuesField(max_length=50,
                                  cast=int,
                                  token=',',
                                  choices=((1, 'start'), (1, 'end')))
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
Beispiel #8
0
class EnglishWordTest(models.Model):

    name = models.CharField(
        max_length=150,
        )

    Words = SeparatedValuesField(
        max_length=150,
        cast=int,
        token=',',
        )
Beispiel #9
0
class Profile(models.Model):
    def __str__(self):
        return str(self.user)

    user = models.OneToOneField(User, on_delete=models.CASCADE)
    watchlist = models.TextField(default='', blank=True)
    watched = SeparatedValuesField(null=True,
                                   max_length=150,
                                   token=',',
                                   choices=(('w', 'Watched'), ('u',
                                                               'Unwatched')))
Beispiel #10
0
class Certificates(models.Model):
    name = models.CharField(max_length=20)
    cover_img_path = models.CharField(max_length=256)
    all_img_paths = SeparatedValuesField(max_length=512, token=',')
    visible = models.BooleanField()

    @property
    def html_name(self):
        return self.name.replace('-', '\n')

    @property
    def description_name(self):
        return self.name.replace('-', ': ')
Beispiel #11
0
class NewsletterList(models.Model):
    name = models.CharField(max_length=255)
    slug = models.SlugField(max_length=255, unique=True)
    description = models.TextField(blank=True, null=True)
    created_at = models.DateTimeField(auto_now_add=True)
    languages = SeparatedValuesField(max_length=50,
                                     blank=True,
                                     null=True,
                                     choices=ALLOWED_LANGUAGES)

    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return reverse('newsletter_list', kwargs={'slug': self.slug})
Beispiel #12
0
class Newsletter(models.Model):
    STATUS_ONLINE = 1
    STATUS_DRAFT = 2

    STATUS_CHOICES = (
        (STATUS_ONLINE, _('Online')),
        (STATUS_DRAFT, _('Draft')),
    )

    name = models.CharField(max_length=255)
    published_at = models.DateTimeField(null=True)
    status = models.PositiveIntegerField(max_length=1,
                                         choices=STATUS_CHOICES,
                                         default=STATUS_DRAFT,
                                         db_index=True)
    headline = models.CharField(max_length=255, blank=True, null=True)
    cover = models.ImageField(upload_to=get_file_path, blank=True, null=True)
    languages = SeparatedValuesField(max_length=50,
                                     blank=True,
                                     null=True,
                                     choices=ALLOWED_LANGUAGES)
    newsletter_list = models.ForeignKey(NewsletterList,
                                        related_name='newsletters')
    sent = models.BooleanField(default=False, db_index=True)

    objects = NewsletterManager()

    def __str__(self):
        return self.name

    def get_previous(self):
        return (self.__class__.objects.filter(
            newsletter_list=self.newsletter_list_id).get_previous(
                self.published_at))

    def get_next(self):
        return (self.__class__.objects.filter(
            newsletter_list=self.newsletter_list_id).get_next(
                self.published_at))

    def is_online(self):
        return self.status == self.STATUS_ONLINE

    def get_absolute_url(self):
        return reverse('newsletter_detail', args=[
            self.pk,
        ])
Beispiel #13
0
class StandardApplication(BaseApplication):
    export_type = models.CharField(choices=ApplicationExportType.choices,
                                   default=None,
                                   max_length=50)
    reference_number_on_information_form = models.CharField(blank=True,
                                                            null=True,
                                                            max_length=255)
    have_you_been_informed = models.CharField(
        choices=ApplicationExportLicenceOfficialType.choices,
        blank=True,
        null=True,
        default=None,
        max_length=50,
    )
    is_shipped_waybill_or_lading = models.BooleanField(blank=True,
                                                       default=None,
                                                       null=True)
    non_waybill_or_lading_route_details = models.TextField(default=None,
                                                           blank=True,
                                                           null=True,
                                                           max_length=2000)
    temp_export_details = models.CharField(blank=True,
                                           default=None,
                                           null=True,
                                           max_length=2200)
    is_temp_direct_control = models.BooleanField(blank=True,
                                                 default=None,
                                                 null=True)
    temp_direct_control_details = models.CharField(blank=True,
                                                   default=None,
                                                   null=True,
                                                   max_length=2200)
    proposed_return_date = models.DateField(blank=True, null=True)
    trade_control_activity = models.CharField(
        choices=TradeControlActivity.choices,
        blank=False,
        null=True,
        max_length=100)
    trade_control_activity_other = models.CharField(blank=False,
                                                    null=True,
                                                    max_length=100)
    trade_control_product_categories = SeparatedValuesField(
        choices=TradeControlProductCategory.choices,
        blank=False,
        null=True,
        max_length=50)
Beispiel #14
0
class OpenApplication(BaseApplication):
    export_type = models.CharField(choices=ApplicationExportType.choices,
                                   default=None,
                                   max_length=50)
    is_shipped_waybill_or_lading = models.BooleanField(blank=True,
                                                       default=None,
                                                       null=True)
    non_waybill_or_lading_route_details = models.TextField(default=None,
                                                           blank=True,
                                                           null=True,
                                                           max_length=2000)
    temp_export_details = models.CharField(blank=True,
                                           default=None,
                                           null=True,
                                           max_length=2200)
    is_temp_direct_control = models.BooleanField(blank=True,
                                                 default=None,
                                                 null=True)
    temp_direct_control_details = models.CharField(blank=True,
                                                   default=None,
                                                   null=True,
                                                   max_length=2200)
    proposed_return_date = models.DateField(blank=True, null=True)
    trade_control_activity = models.CharField(
        choices=TradeControlActivity.choices,
        blank=False,
        null=True,
        max_length=100)
    trade_control_activity_other = models.CharField(blank=False,
                                                    null=True,
                                                    max_length=100)
    trade_control_product_categories = SeparatedValuesField(
        choices=TradeControlProductCategory.choices,
        blank=False,
        null=True,
        max_length=50)
    goodstype_category = models.CharField(choices=GoodsTypeCategory.choices,
                                          blank=False,
                                          null=True,
                                          max_length=100)
    contains_firearm_goods = models.BooleanField(blank=True,
                                                 default=None,
                                                 null=True)
Beispiel #15
0
class CountryOnApplication(models.Model):
    """
    Open licence applications export to countries, instead of an end user
    """

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    application = models.ForeignKey(OpenApplication,
                                    related_name="application_countries",
                                    on_delete=models.CASCADE)
    country = models.ForeignKey(Country,
                                related_name="countries_on_application",
                                on_delete=models.CASCADE)
    contract_types = SeparatedValuesField(max_length=350,
                                          choices=ContractType.choices,
                                          null=True,
                                          default=None)
    other_contract_type_text = models.CharField(max_length=150,
                                                null=True,
                                                default=None)
    flags = models.ManyToManyField(Flag,
                                   related_name="countries_on_applications")
class Project(models.Model):
    name = models.CharField(max_length=150)
    languages = SeparatedValuesField(max_length=150,
                                     choices=(('en', 'English'), ('fr',
                                                                  'French')),
                                     blank=True)
Beispiel #17
0
class DesignDocument(models.Model):
    uploaded_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
    created_at = models.DateTimeField(auto_now_add=True)
    title = models.CharField(max_length=64)
    description = models.TextField(null=True, blank=True)
    has_download = models.BooleanField(default=False)
    has_assets = models.BooleanField(default=False)
    baseline_grid = models.PositiveIntegerField(
        validators=[MaxValueValidator(40)], null=True, blank=True)
    document_grid_x = models.PositiveIntegerField(null=True, blank=True)
    document_grid_y = models.PositiveIntegerField(null=True, blank=True)
    gutter = models.PositiveIntegerField(null=True, blank=True)
    page_dimension_x = models.PositiveIntegerField(null=True, blank=True)
    page_dimension_y = models.PositiveIntegerField(null=True, blank=True)
    margin_top = models.PositiveIntegerField(null=True, blank=True)
    margin_bottom = models.PositiveIntegerField(null=True, blank=True)
    typefaces = SeparatedValuesField(choices=fonts,
                                     token=',',
                                     max_length=64,
                                     null=True,
                                     blank=True)
    weights = SeparatedValuesField(choices=weight_choices,
                                   token=',',
                                   max_length=150,
                                   null=True,
                                   blank=True)
    binding_method = models.CharField(choices=binding_choices,
                                      max_length=128,
                                      null=True,
                                      blank=True)

    def is_favorited(self, user):
        """Returns a boolean telling us if the relevant user has favorited this document"""
        from core.models import UserDocumentFavorite
        if user.is_anonymous:
            return False

        return UserDocumentFavorite.objects.filter(
            user=user, design_document=self).exists()

    @staticmethod
    def format_measurement(dimension1, dimension2, units=""):
        if dimension1 and dimension2:
            return "%s x %s %s" % (dimension1, dimension2, units)

        return 'NA'

    @property
    def number_of_favorites(self):
        from core.models import UserDocumentFavorite

        return UserDocumentFavorite.objects.filter(
            design_document=self).count()

    @property
    def baseline_grid_display(self):
        if not self.baseline_grid:
            return 'NA'

        return "%s pts." % (self.baseline_grid, )

    @property
    def margins_top_bottom(self):
        if not self.margin_top or not self.margin_bottom:
            return "NA"

        return "%s / %s in." % (self.margin_top, self.margin_bottom)

    @property
    def document_grid(self):
        return self.format_measurement(self.document_grid_x,
                                       self.document_grid_y)

    @property
    def page_dimensions(self):

        return self.format_measurement(self.page_dimension_x,
                                       self.page_dimension_y, "in.")
Beispiel #18
0
class Profile(models.Model):
    USER_TYPE_CHOICES = (
        ('recruiter', 'RECRUITER'),
        ('developer', 'DEVELOPER'),
    )
    STAGE_CHOICES = (
        ('profile_type_selection', 'profile_type_selection'),
        ('recuiter_filling_details', 'recuiter_filling_details'),
        ('developer_filling_details', 'developer_filling_details'),
        ('complete', 'complete'),
    )
    GENDER_CHOICES = (
        ('male', 'male'),
        ('female', 'female'),
    )
    YEARS_ACTIVE_CHOICES = (
        ('0-1', '0-1'),
        ('1-2', '1-2'),
        ('2-4', '2-4'),
        ('4-above', '4-above'),
    )

    user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    user_type = models.CharField(choices=USER_TYPE_CHOICES, null=True, blank=True, max_length=30)
    stage = models.CharField(choices=STAGE_CHOICES, default='profile_type_selection', max_length=100)
    profile_photo = models.ImageField(upload_to='users/%Y/%m/%d', blank=True, null=True)
    csa = models.BooleanField(default=False)
    available = models.BooleanField(default=True)
    student = models.BooleanField(default=False)
    gender = models.CharField(choices=GENDER_CHOICES, null=True, blank=True, max_length=30)
    phone_number = models.CharField(null=True, max_length=30)
    # developer profile
    linkedin_url = models.CharField(max_length=500, null=True, )
    portfolio = models.CharField(max_length=500, blank=True, null=True)
    github_repo = models.CharField(max_length=500, null=True, )
    language = models.CharField(max_length=140, null=True, blank=True)
    framework = models.CharField(max_length=140, null=True, blank=True)
    years = models.CharField(choices=YEARS_ACTIVE_CHOICES, null=True, max_length=30)
    about = models.CharField(null=True, max_length=300)
    profile_tags = SeparatedValuesField(null=True, max_length=150, token=',')
    skills = models.CharField(max_length=900, null=True, blank=True)
    verified_skills = models.CharField(max_length=900, null=True, blank=True)
    country = CountryField(null=True, max_length=30)
    availabilty = models.CharField(null=True, max_length=100, blank=True)
    notifications = models.BooleanField(default=True)
    remote_entry = models.BooleanField(default=False)
    remote_verified = models.BooleanField(default=False)

    # years = models.CharField(max_length=30, choices=YEARS_ACTIVE_CHOICES, null=True, blank=True),

    # recruiter profile
    company = models.CharField(max_length=140, null=True, blank=True)
    job_role = models.CharField(max_length=140, null=True, blank=True)
    industry = models.CharField(max_length=80, null=True, blank=True)
    company_url = models.CharField(max_length=500, null=True, blank=True)
    tags = TaggableManager()
    file = CloudinaryField(resource_type="raw", blank=True)
    salary = models.IntegerField(null=True)

    def __str__(self):
        return self.user.username

    def last_seen(self):
        return cache.get('last_seen_%s' % self.user.username)

    def online(self):
        if self.last_seen():
            now = datetime.datetime.now()
            if now > (self.last_seen() + datetime.timedelta(seconds=settings.USER_ONLINE_TIMEOUT)):
                return False
            else:
                return True
        else:
            return False

    def photo(self, default_path="default_user_photo.png"):
        if self.profile_photo:
            return self.profile_photo
        return default_path

    def get_absolute_url(self):
        return '/accounts/profile/'

    @property
    def full_name(self):
        return self.user.get_full_name()

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

    @receiver(post_save, sender=User)
    def create_user_profile(sender, instance, created, **kwargs):
        if created:
            Profile.objects.create(user=instance)

    @receiver(post_save, sender=User)
    def save_user_profile(sender, instance, **kwargs):
        instance.profile.save()
Beispiel #19
0
class Media(models.Model):
    IMAGE = 0
    VIDEO = 1
    AUDIO = 2
    TYPE_CHOICES = (
        (IMAGE, 'Image'),
        (VIDEO, 'Video'),
        (AUDIO, 'Audio'),
    )
    type = models.IntegerField(choices=TYPE_CHOICES)
    title = models.CharField(max_length=255, null=True, blank=True)
    project = models.ForeignKey(Project, null=True, related_name='medias',
                                on_delete=models.SET_NULL)
    created_at = models.DateTimeField(default=datetime.now)
    realized_at = models.DateTimeField(null=True)
    country = CountryField(null=True)
    city = models.ForeignKey(City, null=True, on_delete=models.SET_NULL)
    position = models.PositiveIntegerField(null=True)

    image = models.ImageField(upload_to=get_image_path,
                              blank=True,
                              null=True)

    video = models.FileField(upload_to=get_video_path, null=True, blank=True)

    audio = models.FileField(upload_to=get_audio_path, null=True, blank=True)

    thumbnail_file = models.ImageField(upload_to=get_image_path,
                                       blank=True,
                                       null=True)
    languages = SeparatedValuesField(max_length=255,
                                     blank=True,
                                     null=True)

    url = models.URLField(blank=True, null=True)

    tags = models.ManyToManyField(Tag)

    def next_media(self):
        default = Media.objects.filter(project=self.project, id__gt=self.id).first()
        return Media.objects.filter(project=self.project, position=self.position+1).first() if self.position else default or default

    def is_video_file(self):
        return self.video.name.endswith(VIDEO_FILE_EXTENSION)

    def upload_to_vimeo(self):
        if not self.video.name or not hasattr(settings, 'VIMEO_CLIENT_ID'):
            return

        v = vimeo.VimeoClient(token=settings.VIMEO_CLIENT_TOKEN,
                              key=settings.VIMEO_CLIENT_ID,
                              secret=settings.VIMEO_CLIENT_SECRET)

        vimeo_account_data = v.get('/me').json()

        if self.video.file.size > vimeo_account_data['upload_quota']['space']['free']:
            # TODO send email to zim and I
            return

        data = {
                'type' : 'pull',
                'link' : self.video.url
        }

        response = v.post('/me/videos', data=data).json()
        self.url = response.get('link')
        self.save()
        self.edit_vimeo_information()

    def edit_vimeo_information(self, change_thumbnail=False):
        if not self.url or not hasattr(settings, 'VIMEO_CLIENT_ID'):
            return

        video_uri = self.url.split('https://vimeo.com/')
        if len(video_uri) != 2:
            return

        video_uri = '/videos/%s' % video_uri[1]

        v = vimeo.VimeoClient(token=settings.VIMEO_CLIENT_TOKEN,
                              key=settings.VIMEO_CLIENT_ID,
                              secret=settings.VIMEO_CLIENT_SECRET)

        v.patch(video_uri, data={'name': self.title_en})
        v.put('%s/tags' % video_uri, data=[{'tag': tag.name_en} for tag in self.tags.all()])

        if self.thumbnail_file and change_thumbnail:
            with tempfile.NamedTemporaryFile() as temp:
                temp.write(self.thumbnail_file.file.read())
                v.upload_picture(video_uri, temp.name, activate=True)

    def transform_audio_to_video(self):
        # if (self.type != self.AUDIO
        #     or not self.audio
        #     or not self.thumbnail_file):
        #     return None

        # audio_split = self.audio.url.split('/')
        # audio_file_name = audio_split[len(audio_split) - 1]
        # audio_name = audio_file_name.split('.')[0]

        # image_clip = ImageClip(self.thumbnail_file.url)
        # audio_clip = AudioFileClip(self.audio.url)

        # clip = image_clip.set_audio(audio_clip)
        # clip = clip.set_duration(audio_clip.duration)

        # with tempfile.NamedTemporaryFile(suffix='%s.mp4' % audio_name) as temp:
        #     clip.write_videofile(temp.name, fps=1)
        #     self.video = SimpleUploadedFile('%s.mp4' % audio_name, temp.file.read(), content_type='video/mp4')
        #     self.save()
        #     self.upload_to_vimeo()
        pass

    class Meta:
        abstract = False
        db_table = 'mnemotopy_project_media'
Beispiel #20
0
class RandomQuiz(models.Model):
    quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE, related_name='tempquiz')
    student = models.ForeignKey(Student, on_delete=models.CASCADE, related_name='tempanswers')
    questions =SeparatedValuesField(null=True,max_length=150,token=',')
Beispiel #21
0
class RoutingRule(TimestampableModel):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    team = models.ForeignKey(Team,
                             related_name="routing_rules",
                             on_delete=models.CASCADE)
    queue = models.ForeignKey(
        Queue,
        related_name="routing_rules",
        on_delete=models.DO_NOTHING,
    )
    status = models.ForeignKey(
        CaseStatus,
        related_name="routing_rules",
        on_delete=models.DO_NOTHING,
    )
    tier = models.PositiveSmallIntegerField(
    )  # positive whole number, that decides order routing rules are applied
    additional_rules = SeparatedValuesField(
        choices=RoutingRulesAdditionalFields.choices,
        max_length=100,
        blank=True,
        null=True,
        default=None)
    active = models.BooleanField(default=True)

    # optional fields that are required depending on values in additional_rules
    user = models.ForeignKey(GovUser,
                             related_name="routing_rules",
                             on_delete=models.DO_NOTHING,
                             blank=True,
                             null=True)
    case_types = models.ManyToManyField(CaseType,
                                        related_name="routing_rules",
                                        blank=True)
    flags_to_include = models.ManyToManyField(Flag,
                                              related_name="routing_rules",
                                              blank=True)
    flags_to_exclude = models.ManyToManyField(
        Flag, related_name="exclude_routing_rules", blank=True)
    country = models.ForeignKey(Country,
                                related_name="routing_rules",
                                on_delete=models.DO_NOTHING,
                                blank=True,
                                null=True)

    class Meta:
        indexes = [models.Index(fields=["created_at", "tier"])]
        ordering = ["team__name", "tier", "-created_at"]

    def parameter_sets(self):
        """
        Generate a list of sets, containing all the possible subsets of the rule which are true to the condition
            of routing rules. We generate one set for each case_type as we can not have multiple case_types in the set
            (would cause all rules to fail)
        :return: list of sets
        """

        parameter_sets = []

        # Exclude the rule by returning and empty list if there are any inactive flags in the rule
        if (self.flags_to_include.exclude(status=FlagStatuses.ACTIVE).exists()
                or self.flags_to_exclude.exclude(
                    status=FlagStatuses.ACTIVE).exists()):
            return parameter_sets

        country_set = {self.country} if self.country else set()

        flag_and_country_set = set(self.flags_to_include.all()) | country_set

        for case_type in self.case_types.all():
            parameter_set = {
                "flags_country_set": flag_and_country_set | {case_type}
            }
            if self.flags_to_exclude:
                parameter_set["flags_to_exclude"] = set(
                    self.flags_to_exclude.all())

            parameter_sets.append(parameter_set)

        if not parameter_sets:
            parameter_sets = [
                {
                    "flags_country_set": flag_and_country_set,
                    "flags_to_exclude": set(self.flags_to_exclude.all())
                },
            ]

        return parameter_sets
class ProjectCastInt(models.Model):
    name = models.CharField(max_length=150)
    languages = SeparatedValuesField(max_length=150,
                                     cast=int,
                                     choices=((1, 'English'), (2, 'French')))
class ProjectCastString(models.Model):
    name = models.CharField(max_length=150)
    languages = SeparatedValuesField(max_length=150,
                                     choices=(('1', 'English'), ('2',
                                                                 'French')))
Beispiel #24
0
class Institution(models.Model):
    #define your columns here
    institute_id = models.IntegerField(auto_created=True,
                                       primary_key=True,
                                       editable=False,
                                       help_text="Institution ID")
    name = models.CharField(
        max_length=200,
        blank=False,
        null=False,
        db_index=True,
        editable=True,
        verbose_name='Institution Name',
        help_text='Institution Name. Users will search by name.')
    address = models.CharField(
        max_length=200,
        blank=False,
        null=False,
        db_index=False,
        editable=True,
        verbose_name='Address',
        help_text='Site No, Street Name and other address related details')
    city = models.CharField(max_length=100,
                            blank=False,
                            null=False,
                            db_index=False,
                            editable=True,
                            verbose_name='City',
                            help_text='City')
    state = models.CharField(max_length=50,
                             blank=False,
                             null=False,
                             db_index=False,
                             editable=True,
                             verbose_name='State',
                             help_text='State')
    start_class_level = models.CharField(
        max_length=20,
        blank=False,
        null=False,
        db_index=False,
        editable=True,
        verbose_name='Starting class level',
        help_text=
        'State the lowest class level at which kids can get admitted to the institution'
    )
    end_class_level = SeparatedValuesField(
        max_length=200,
        blank=False,
        null=False,
        db_index=False,
        editable=True,
        choices=DEGREES,
        verbose_name='Highest class level',
        help_text=
        'State the highest class level till which students can study in the institute'
    )

    class Meta:
        verbose_name_plural = 'Institutions'
        ordering = ['name']

    def get_absolute_url(self):
        return reverse('view-institute-details',
                       kwargs={'institute_id': str(self.pk)})

    # Override the __unicode__() method to return out something meaningful!
    def __unicode__(self):
        return '{0} - {1} - {2}'.format(self.name, self.address, self.state)