Ejemplo n.º 1
0
class ActivitySearch(models.Model):
    activity = models.OneToOneField('Activity')
    iati_identifier = VectorField()
    text = VectorField()
    title = VectorField()
    description = VectorField()
    reporting_org = VectorField()
    participating_org = VectorField()
    recipient_country = VectorField()
    recipient_region = VectorField()
    sector = VectorField()
    document_link = VectorField()
    last_reindexed = models.DateTimeField()
Ejemplo n.º 2
0
class Course(models.Model):
    code = models.CharField(max_length=20)
    title = models.CharField(max_length=255)
    description = models.TextField(blank=True, null=True)
    dept = models.ForeignKey(Department, related_name='courses')
    slug = models.SlugField(blank=True)
    lookup = models.CharField(max_length=276)
    search_index = VectorField()

    objects = CourseManager(field_name='code',
                            fields=('code', 'title', 'description'),
                            auto_update_search_field=True)

    def natural_key(self):
        return self.code

    def get_absolute_url(self):
        return reverse('course_detail', kwargs={'course_slug': self.slug})

    def __unicode__(self):
        return '{0} - {1}'.format(self.code, self.title)

    def save(self, *args, **kwargs):
        self.lookup = self.title
        self.slug = slugify(self.code)
        super(Course, self).save(*args, **kwargs)
Ejemplo n.º 3
0
class Human(MPTTModel):
    full_name = models.CharField(max_length=150,
                                 default="",
                                 verbose_name='ФИО')
    """position = models.ForeignKey(Position, null=True, on_delete=models.SET_NULL, verbose_name='Должность')"""
    position = models.CharField(max_length=150, verbose_name='Должность')
    employment_date = models.DateField(auto_now=False,
                                       verbose_name='Дата прийома на работу')
    salary = models.IntegerField(verbose_name='Зарплата')
    parent = TreeForeignKey('self',
                            on_delete=models.SET_NULL,
                            null=True,
                            blank=True,
                            related_name="children",
                            verbose_name='Начальник')

    search_index = VectorField()

    search_manager = SearchManager(fields=('full_name', 'position'),
                                   config='pg_catalog.russian',
                                   search_field='search_index',
                                   auto_update_search_field=True)

    class MPTTMeta:
        unique_together = (('full_name', 'parent'), )

    def __str__(self):
        return self.full_name
Ejemplo n.º 4
0
class Fingerprint(models.Model):
    ip = models.GenericIPAddressField()
    port = models.PositiveIntegerField()
    service = models.CharField(max_length=64, blank=True)

    os = models.CharField(max_length=32, blank=True)
    info = models.CharField(max_length=256, blank=True)
    product = models.CharField(max_length=256, blank=True)
    hostname = models.CharField(max_length=128, blank=True)
    device = models.CharField(max_length=128, blank=True)
    version = models.CharField(max_length=128, blank=True)
    cpes = ArrayField(models.CharField(max_length=128), default=[])

    certificate = JSONField(default={})
    banner = models.TextField()
    raw = models.TextField()

    timestamp = models.DateTimeField(auto_now=True)

    search_index = VectorField(db_index=False)
    objects = SearchManager(
        fields=('os', 'info', 'service', 'product', 'hostname', 'device', 'version', 'banner'),
        config='chinese',
        search_field='search_index',
        auto_update_search_field=True
    )

    def __str__(self):
        return '%s:%d' % (self.ip, self.port)
Ejemplo n.º 5
0
class Document(models.Model):
    title = models.CharField(max_length=200)
    pub_date = models.DateTimeField(auto_now_add=True)
    modified_date = models.DateTimeField(auto_now=True)
    body = models.TextField()
    url = models.CharField(max_length=500)
    entities = models.ManyToManyField(Entity)
    feed = models.ForeignKey(Feed)
    cluster = models.ForeignKey(Cluster, null=True, blank=True)

    search_index = VectorField()
    objects = SearchManager(fields=('title', 'body'),
                            config='pg_catalog.english',
                            search_field='search_index',
                            auto_update_search_field=True)

    def content(self):
        text = self.title
        if self.body:
            text = text + ' \n\n' + self.body
        return text

    def highlighted(self):
        return Highlighter.highlight_text(self.content(), None,
                                          self.entities.all())

    def num_entities(self):
        return self.entities.count()

    def __str__(self):
        return self.title
Ejemplo n.º 6
0
class Professor(models.Model):
    midd_webid = models.CharField(max_length=32,
                                  blank=True,
                                  null=True,
                                  unique=True)
    first = models.CharField(max_length=100, blank=True, null=True)
    last = models.CharField(max_length=100)
    dept = models.ForeignKey(Department, related_name='professors')
    email = models.EmailField(blank=True, null=True)
    slug = models.SlugField(blank=True)
    lookup = models.CharField(max_length=201)
    search_index = VectorField()

    objects = ProfessorManager(field_name='last',
                               fields=('first', 'last', 'email'),
                               auto_update_search_field=True)

    def natural_key(self):
        return self.last

    def get_absolute_url(self):
        return reverse('prof_detail', kwargs={'prof_slug': self.slug})

    def __unicode__(self):
        return '{0} {1}'.format(self.first, self.last)

    def save(self, *args, **kwargs):
        self.slug = slugify('{0}-{1}'.format(self.first, self.last))
        self.lookup = unicode(self)
        super(Professor, self).save(*args, **kwargs)
Ejemplo n.º 7
0
class Record(models.Model):
    form = models.ForeignKey('form_designer.Form')
    environment = models.ForeignKey('appstore.Environment')

    data = jsonfield.JSONField(db_type='json')
    text_data = models.TextField()

    string_representation = models.CharField(max_length=100, blank=True)

    search_index = VectorField()
    objects = SearchManager(fields=('text_data', ),
                            auto_update_search_field=True)

    def get_absolute_url(self):
        return reverse('formapp_record_detail', args=(self.pk, ))

    def __unicode__(self):
        return self.string_representation

    @property
    def feature(self):
        return self.form.appform.app.provides

    class Meta:
        ordering = ('text_data', )
Ejemplo n.º 8
0
class Book(models.Model):
    author = models.ForeignKey(Person)
    name = models.CharField(max_length=32)
    search_index = VectorField()

    objects = SearchManager(fields=('name', ),
                            search_field='search_index',
                            auto_update_search_field=True,
                            config='names')

    def __str__(self):
        return self.name
Ejemplo n.º 9
0
class Person3(models.Model):
    name = models.CharField(max_length=32)
    description = models.TextField()
    search_index = VectorField()

    objects = SearchManager(fields=('name', 'description'),
                            search_field='search_index',
                            auto_update_search_field=True,
                            config='names')

    def __str__(self):
        return self.name
Ejemplo n.º 10
0
class Person4(models.Model):
    INDEXED_KEY = 'indexed_key'

    name = models.CharField(max_length=32)
    description = models.TextField()
    data = models.TextField(default='{}')

    search_index = VectorField()
    data_search_index = VectorField()

    objects = SearchManager(fields=('name', 'description'),
                            search_field='search_index',
                            auto_update_search_field=True,
                            config='names')

    def __str__(self):
        return self.name

    def update_search_field(self, **kwargs):
        self._fts_manager.update_search_field(**kwargs)
        self._fts_manager.update_search_field(search_field='data_search_index',
                                              fields=('data', ),
                                              config='names',
                                              extra={
                                                  'key': self.INDEXED_KEY,
                                              })

    @staticmethod
    def _convert_field_to_db(field, weight, config, using, extra=None):
        if field.name != 'data':
            # Use the default converter
            return

        connection = connections[using]
        qn = connection.ops.quote_name

        return "setweight(to_tsvector('%s', coalesce(to_json(%s.%s::json) ->> '%s', '')), '%s')" % (
            config, qn(field.model._meta.db_table), qn(
                field.column), extra['key'], weight)
Ejemplo n.º 11
0
class Person2(models.Model):
    name = models.CharField(max_length=32)
    description = models.TextField()
    search_index = VectorField()

    objects = SearchManager(
        fields=(('name', 'A'), ('description', 'B')),
        search_field='search_index',
        config='names',
    )

    def __str__(self):
        return self.name
Ejemplo n.º 12
0
class Performer(Agent):
    performer_id = models.AutoField(primary_key=True)
    about = models.CharField(max_length=255, blank=True)
    bio = models.TextField(blank=True)
    artists_we_like = models.CharField(max_length=255, blank=True)
    band_members = models.CharField(max_length=255, blank=True)
    booking_agent = models.CharField(max_length=255, blank=True)
    category = models.CharField(max_length=255, blank=True)
    cover_id = models.IntegerField(blank=True, null=True)
    cover_source = models.CharField(max_length=1000, blank=True)
    current_location = models.CharField(max_length=255, blank=True)
    description = models.TextField(blank=True)
    genre = models.CharField(max_length=255, blank=True)
    hometown = models.CharField(max_length=255, blank=True)
    likes = models.IntegerField(blank=True, null=True)
    link = models.CharField(max_length=255, blank=True)
    band_type = models.CharField(max_length=55)
    record_label = models.CharField(max_length=255, blank=True)
    talking_about_count = models.PositiveIntegerField(null=True)
    website = models.CharField(max_length=255, blank=True)
    twitter_handle = models.CharField(max_length=255, blank=True)
    sound_path = models.URLField(max_length=500, blank=True)
    created = models.DateTimeField(auto_now_add=True)
    edited = models.DateTimeField(blank=True, null=True, auto_now=True)
    email_address = models.EmailField(max_length=255, blank=True)
    deleted = models.BooleanField(default=0)
    # Foreign
    location = models.ForeignKey(Location,
                                 models.DO_NOTHING,
                                 blank=True,
                                 null=True)
    events = models.ManyToManyField(Event)
    genres = models.ManyToManyField(Genre, through="PerformerGenre")
    accounts = models.ManyToManyField(Account)

    #Fulltextindex
    genre_index = VectorField()
    objects = SearchManager(
        fields=(('about', 'A'), ('bio', 'B'), ('genre', 'A'), ('description',
                                                               'B')),
        config='pg_catalog.english',  # this is default
        search_field='genre_index',  # this is default
        auto_update_search_field=True)

    # fts_index = TSVectorField(
    #     (('about', 'A'), ('bio', 'B'), ('genre', 'A'), ('description', 'B')),
    #     dictionary='english'
    # )

    def __str__(self):
        return self.name
Ejemplo n.º 13
0
class Document(models.Model):
    title = models.CharField(max_length=200)
    text = models.TextField()

    search_index = VectorField()

    objects = SearchManager(
        fields=(('title', 'A'), ('text', 'D')),
        config='pg_catalog.english',  # this is default
        search_field='search_index',  # this is default
        auto_update_search_field=True)

    def __str__(self):
        return self.title
Ejemplo n.º 14
0
class Contract(models.Model):

    idv_piid = models.CharField(max_length=128) #index this field
    piid = models.CharField(max_length=128) #index this field
    contract_start = models.DateField(null=True, blank=True)
    contract_end = models.DateField(null=True, blank=True)
    contract_year = models.IntegerField(null=True, blank=True)
    vendor_name = models.CharField(max_length=128)
    labor_category = models.TextField(db_index=True)
    education_level = models.CharField(db_index=True, choices=EDUCATION_CHOICES, max_length=5, null=True, blank=True)
    min_years_experience = models.IntegerField(db_index=True)
    hourly_rate_year1 = models.DecimalField(max_digits=10, decimal_places=2)
    hourly_rate_year2 = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True)
    hourly_rate_year3 = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True)
    hourly_rate_year4 = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True)
    hourly_rate_year5 = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True)
    current_price = models.DecimalField(db_index=True, max_digits=10, decimal_places=2, null=True, blank=True)
    next_year_price = models.DecimalField(db_index=True, max_digits=10, decimal_places=2, null=True, blank=True)
    second_year_price = models.DecimalField(db_index=True, max_digits=10, decimal_places=2, null=True, blank=True)
    contractor_site = models.CharField(db_index=True, max_length=128, null=True, blank=True)
    schedule = models.CharField(db_index=True, max_length=128, null=True, blank=True)
    business_size = models.CharField(db_index=True, max_length=128, null=True, blank=True)
    sin = models.TextField(null=True, blank=True)

    search_index = VectorField()

    #use a manager that filters by current contracts with a valid current_price
    objects = CurrentContractManager(
        fields=('labor_category',),
        config = 'pg_catalog.english',
        search_field='search_index',
        auto_update_search_field = True
    )

    def get_readable_business_size(self):
        if 's' in self.business_size.lower():
            return 'small business'
        else:
            return 'other than small business'

    def get_education_code(self, text):

        for pair in EDUCATION_CHOICES:
            if text.strip() in pair[1]:
                return pair[0]

        return None

    def normalize_rate(self, rate):
        return float(rate.replace(',', '').replace('$', ''))
Ejemplo n.º 15
0
class Post(models.Model):
    class Meta:
        verbose_name = 'Статья'
        verbose_name_plural = 'Статьи'
        ordering = ['-created']
        db_table = 'article'

    title = models.CharField(max_length=200, verbose_name='Заголовок')
    body = RichTextUploadingField(
        verbose_name='Статья',
        config_name='default')  #models.TextField(verbose_name='Статья')
    slug = models.SlugField(max_length=200, unique=True, verbose_name='Ссылка')
    created = models.DateTimeField(auto_now_add=True,
                                   verbose_name='Дата создания')
    image = models.ImageField(upload_to='post',
                              blank=True,
                              default='post/default.jpg')
    pageviews = models.PositiveIntegerField(
        verbose_name='Количество просмотров', default=0, blank=True)
    tags = TaggableManager(through=RuTaggedItem)  #through=RuTaggedItem
    category = models.ForeignKey(Category,
                                 default='',
                                 verbose_name='Категория')
    description = models.TextField(blank=True,
                                   null=True,
                                   verbose_name='Описание')

    search_index = VectorField()
    objects = SearchManager(fields=('title', 'description'),
                            config='pg_catalog.russian',
                            search_field='search_index',
                            auto_update_search_field=True)

    def __str__(self):
        return self.title

    def get_object(self):
        return get_object_or_404(Post, slug__iexact=self.kwargs['slug'])

    def get_absolute_url(self):
        return reverse("article_detail", kwargs={"slug": self.slug})

    def image_tag(self):
        if self.image:
            return u'<img src="%s" style="width:100px" />' % self.image.url
        else:
            return '(нет изображения)'

    image_tag.short_description = 'Изображение'
    image_tag.allow_tags = True
Ejemplo n.º 16
0
class Subject(models.Model):
    description = models.CharField(max_length=300, null=False, blank=False, unique=True)

    search_index = VectorField()

    objects = SearchManager(
        fields=('description', ),
        config='pg_catalog.english',
        search_field='search_index',
        auto_update_search_field=True
    )
    search_subject = SubjectManager()

    def __unicode__(self):
        return self.description
Ejemplo n.º 17
0
class Page(models.Model):
    url = models.CharField(max_length=255, primary_key=True)
    title = models.CharField(max_length=255, blank=True)
    text = models.TextField(blank=True)
    lang = models.CharField(max_length=2, blank=True)
    search_index = VectorField()

    objects = models.Manager()
    search_manager = SearchManager(fields=('title', 'text'),
                                   config='pg_catalog.russian',
                                   search_field='search_index',
                                   auto_update_search_field=True)

    def __str__(self):
        return self.url
Ejemplo n.º 18
0
class Card(BaseCard):
    box = models.ForeignKey(Box, related_name="cards", verbose_name="kort")
    search_index = VectorField()
    objects = SearchManager(fields=('name', 'ocr_text'),
                            config='pg_catalog.swedish',
                            search_field='search_index',
                            auto_update_search_field=True)

    # readonly field to show preview pic in django admin interface
    def image_tag(self):
        return """<img style="width:450px" alt="Kort %s" src="/static/%s/%s" />""" % (
            self.catalog_sequence_number, settings.HSNOMINAL_CARDS_SUBFOLDER,
            self.box.folder_name + "/" + self.filename)

    image_tag.short_description = 'Bild'
    image_tag.allow_tags = True
Ejemplo n.º 19
0
class Network(models.Model):
    network = CidrAddressField(primary_key=True)
    name = models.CharField(max_length=255, blank=True, null=True)
    gateway = InetAddressField(blank=True, null=True)
    description = models.TextField(blank=True, null=True)
    vlans = models.ManyToManyField(
        "Vlan", through="NetworkToVlan", related_name="vlan_networks"
    )
    dhcp_group = models.ForeignKey(
        "DhcpGroup", db_column="dhcp_group", blank=True, null=True
    )
    shared_network = models.ForeignKey(
        "SharedNetwork", db_column="shared_network", blank=True, null=True
    )
    changed = models.DateTimeField(auto_now=True)
    changed_by = models.ForeignKey(settings.AUTH_USER_MODEL, db_column="changed_by")

    search_index = VectorField()

    # objects = NetworkQuerySet.as_manager()
    objects = NetworkManager.from_queryset(NetworkQuerySet)()

    searcher = SearchManager(
        fields=("name", "description"),
        config="pg_catalog.english",  # this is default
        search_field="search_index",  # this is default
        auto_update_search_field=True,
    )

    tags = TaggableManager(through=TaggedNetworks, blank=True)

    # Forcing pk as string
    @property
    def pk(self):
        return str(self.network)

    def __str__(self):
        return "%s" % self.network

    class Meta:
        db_table = "networks"
        permissions = (
            ("is_owner_network", "Is owner"),
            ("add_records_to_network", "Can add records to"),
        )
        default_permissions = ("add", "change", "delete", "view")
        ordering = ("network",)
Ejemplo n.º 20
0
class Person(models.Model):
    name = models.CharField(max_length=32)
    description = models.TextField()
    search_index = VectorField()

    objects = SearchManager(
        fields=('name', 'description'),
        search_field='search_index',
        config='names',
    )

    def __str__(self):
        return self.name

    def save(self, *args, **kwargs):
        super(Person, self).save(*args, **kwargs)
        self.update_search_field()
Ejemplo n.º 21
0
class PermitData(models.Model):
    # Attach this PermitData object to a specific PermitArea object
    owner = models.ForeignKey(PermitArea, related_name='data')

    # These are basic fields supported by all the municipalities that we
    # currently pull data from. They are all character fields.
    name = models.CharField(max_length=1024, null=True)
    proj_id = models.CharField(max_length=1024, null=True)
    #link = models.CharField(max_length=1024, null=True)
    info_link = models.ForeignKey(InfoLink, null=True)
    status = models.CharField(max_length=1024, null=True)
    comment = models.TextField(null=True)
    # We also store this here in case it changes over time.
    # Having it here also gives us full text search on category
    category = models.CharField(max_length=1024, null=True)

    # Date on which the values in this row were captured
    saved_on = models.DateField()

    # We must use a GeoManager because of our foreign key relation to the
    # PermitArea object. Otherwise we'll get errors.
    objects = GeoManager()

    VALUE_FIELDS = ('name', 'comment', 'proj_id', 'status', 'category')

    # In order to support full text search, we have a SECOND model
    # that allows for that access pattern. Attempts to use the GIS
    # mixin that is available in the pgfulltext module failed
    # miserably, so we go with this route for now. The main drawback
    # is that we must manually update the search fields on save
    # because this is not the default manager. That's not too terrible,
    # however, because we only ever save from one place inside kmlutils.py.
    search_index = VectorField()
    text = SearchManager(
        # List all the fields that you want indexed
        fields=VALUE_FIELDS,
        # This may be redundant now. Not sure.
        auto_update_search_field=False)

    @classmethod
    def create_query_dict(cls, area, data_dict):
        for field in PermitData.VALUE_FIELDS:
            if field not in data_dict:
                data_dict[field] = None
        data_dict['owner'] = area
        return data_dict
Ejemplo n.º 22
0
class Note(TimeStampedModel):
    title = models.CharField(max_length=100)
    body = models.TextField()
    raw_body = models.TextField()
    name = models.CharField(max_length=50)
    tags = models.ManyToManyField("Tag",
                                  related_name="notes",
                                  through="NoteTagRelation")

    search_index = VectorField()

    objects = SearchManager(fields=(("title", "A"), ("tags__title", "B"),
                                    ("raw_body", "D")),
                            auto_update_search_field=True)

    def __unicode__(self):
        return self.title
Ejemplo n.º 23
0
class SearchIndex(models.Model):
    backoffice_instance = models.CharField(max_length=32)
    model_slug = models.CharField(max_length=32)
    model_id = models.PositiveIntegerField()
    to_index = models.TextField(blank=True)

    search_index = VectorField()

    objects = SearchManager(fields=('to_index', ),
                            search_field='search_index',
                            auto_update_search_field=True)

    class Meta:
        verbose_name = u'search index entry'
        verbose_name_plural = u'search index entries'

    def __unicode__(self):
        return u'%s/%s/%d' % (self.backoffice_instance, self.model_slug,
                              self.model_id)
Ejemplo n.º 24
0
class Story(models.Model):
    title = models.TextField()
    url = models.URLField()
    date = models.DateField()
    primary_image = models.URLField(null=True)
    primary_image_caption = models.TextField(null=True)
    primary_image_rights_information = models.TextField(null=True)
    subjects = models.TextField(null=True)
    station = models.TextField(null=True)
    state = models.TextField(null=True)
    place = models.TextField(null=True)
    keywords = models.TextField(null=True)
    location = PointField()

    search_index = VectorField()

    objects = SearchManager(fields=('title', 'primary_image_caption'),
                            config='pg_catalog.english',
                            search_field='search_index',
                            auto_update_search_field=True)
Ejemplo n.º 25
0
class Topic(models.Model):
    PROGRAM_CHOICES = (
        ("SBIR", "SBIR"),
        ("STTR", "STTR"),
    )

    topic_number = models.TextField(unique=True)
    solicitation = models.ForeignKey(Solicitation, related_name='solicitation')
    url = models.TextField(unique=True)
    title = models.TextField()
    agency = models.TextField(blank=True, null=True)
    program = models.CharField(max_length=10, choices=PROGRAM_CHOICES)
    description = models.TextField()
    objective = models.TextField()
    fts = VectorField()
    saved_by = models.ManyToManyField(settings.AUTH_USER_MODEL,
                                      blank=True,
                                      null=True,
                                      related_name='saved_topics')

    objects = SearchManager(fields=None,
                            search_field='fts',
                            auto_update_search_field=False)
Ejemplo n.º 26
0
class Website(models.Model):
    domain = models.CharField(max_length=64)
    ip = models.GenericIPAddressField()
    port = models.IntegerField(default=80)
    title = models.TextField(blank=True)

    url = models.CharField(max_length=512)
    headers = JSONField(default={})
    raw_headers = models.TextField(blank=True)
    html = models.TextField()  # full html source
    app_joint = models.CharField(max_length=256, default='')  # ' '.join(apps), for full search

    timestamp = models.DateTimeField(auto_now=True)

    search_index = VectorField(db_index=False)
    objects = SearchManager(
        fields=('domain', 'url', 'raw_headers', 'app_joint', 'html', 'title'),
        config='chinese',
        search_field='search_index',
        auto_update_search_field=True
    )

    def __str__(self):
        return self.title
Ejemplo n.º 27
0
class Exercise(TimeStampedModel):
    user = models.ForeignKey(settings.AUTH_USER_MODEL,
                             verbose_name=_('Created by'))
    title = models.CharField(max_length=155, verbose_name=_('Title'))
    slug = models.SlugField(_("Slug"), unique_for_date='created', default='')

    description = models.TextField(verbose_name=_('Description'))

    solution_text = models.TextField(verbose_name=_('Text solution'))
    solution_file = models.FileField(verbose_name=_('File solution'),
                                     blank=True,
                                     null=True)

    search_index = VectorField()

    objects = SearchManager(fields=('title', 'description'),
                            config='pg_catalog.english',
                            search_field='search_index',
                            auto_update_search_field=True)

    tags = TaggableManager()

    def __unicode__(self):
        return self.title
Ejemplo n.º 28
0
class Event(models.Model):
    REPEAT_CHOICES = (
        ('D', 'Daily'),
        ('W', 'Weekly'),
        ('Y', 'Yearly'),
    )

    ACCESS_LEVEL_CHOICES = (('PUBLIC', 'public'), ('PRIVATE', 'private'),
                            ('CONNECTIONS', 'connections'))

    class Meta:
        permissions = (("view_event", "View event"), )

    description = models.TextField(null=True, blank=True)
    name = models.CharField(max_length=300)
    event_type = models.CharField(max_length=50, default='persice')
    location = GeopositionField(default="0,0", blank=True, null=True)
    point = models.PointField(null=True)
    # "name": "Guadalupe St & W 17th St (outside of Dive Bar & Lounge)"
    location_name = models.CharField(max_length=255, null=True)
    country = models.CharField(max_length=255, null=True)
    # "name": "Guadalupe St & W 17th St (outside of Dive Bar & Lounge)"
    full_address = models.CharField(max_length=255, null=True)
    starts_on = models.DateTimeField(null=True, blank=True)
    ends_on = models.DateTimeField(null=True, blank=True)
    repeat = models.CharField(max_length=1, choices=REPEAT_CHOICES)
    street = models.CharField(max_length=300, null=True, blank=True)
    city = models.CharField(max_length=100, null=True, blank=True)
    zipcode = models.CharField(max_length=7, null=True, blank=True)
    state = models.CharField(max_length=3, null=True, blank=True)
    members = models.ManyToManyField(FacebookCustomUser, through='Membership')
    max_attendees = models.IntegerField(default=10)
    access_level = models.CharField(choices=ACCESS_LEVEL_CHOICES,
                                    default=ACCESS_LEVEL_CHOICES[0],
                                    max_length=20)
    access_user_list = models.TextField(null=True, blank=True)
    event_photo = ThumbnailerImageField(null=True,
                                        upload_to='event_photos/%Y/%m/%d')
    eid = models.BigIntegerField(blank=True, null=True)
    event_url = models.URLField(blank=True, null=True)

    search_index = VectorField()

    # geo_objects = gis_models.GeoManager()
    objects = GeoPgFullTextManager(fields=('description', 'name'),
                                   config='pg_catalog.english',
                                   search_field='search_index',
                                   auto_update_search_field=True)

    def __unicode__(self):
        return self.name

    def save(self, *args, **kwargs):
        if self.location:
            point = fromstr("POINT(%s %s)" %
                            (self.location.longitude, self.location.latitude))
            self.point = point
        super(Event, self).save(*args, **kwargs)

    @property
    def organizer(self):
        organizer = self.membership_set.filter(is_organizer=True).first()
        return organizer.user if organizer else None
Ejemplo n.º 29
0
class Submission(models.Model):
    def user_display_name(self):
        return self.voter.user_display_name()

    category = models.ForeignKey(Category)
    idea = models.TextField(verbose_name=_('Question'))

    headline = models.TextField(null=False, blank=False)
    followup = models.TextField(null=True, blank=True)

    citation = models.CharField(
        max_length=2000,
        null=True,
        blank=True,
        db_index=True,
        verbose_name=_("Optional link to full proposal or reference"))
    citation_verified = models.BooleanField(default=False, db_index=True)

    voter = models.ForeignKey("Voter")
    created_at = models.DateTimeField(db_index=True)

    ip_address = models.CharField(max_length=255, db_index=True)

    editors_pick = models.BooleanField(default=False)
    approved = models.BooleanField(default=False, db_index=True)

    # if True, will not show up again in moderation list.
    moderated_removal = models.BooleanField(default=False, db_index=True)

    has_duplicates = models.BooleanField(default=False, db_index=True)

    duplicate_of = models.ForeignKey('opendebates.Submission',
                                     null=True,
                                     blank=True,
                                     related_name="duplicates")

    votes = models.IntegerField(default=0, db_index=True)
    local_votes = models.IntegerField(default=0, db_index=True)
    score = models.FloatField(default=0, db_index=True)
    rank = models.FloatField(default=0, db_index=True)

    random_id = models.FloatField(default=0, db_index=True)

    search_index = VectorField()

    keywords = models.TextField(null=True, blank=True)

    objects = SearchManager(fields=["idea", "keywords"],
                            auto_update_search_field=True)

    source = models.CharField(max_length=255, null=True, blank=True)

    happened = models.DateField(null=True, blank=True)
    is_positive = models.BooleanField(default=False)

    class Meta:
        ordering = ['-happened']

    def get_recent_votes(self):
        timespan = datetime.datetime.now() - datetime.timedelta(1)
        return Vote.objects.filter(submission=self,
                                   created_at__gte=timespan).count()

    def get_duplicates(self):
        if not self.has_duplicates:
            return None
        return Submission.objects.select_related(
            "voter", "category", "voter__user").filter(approved=True,
                                                       duplicate_of=self)

    def __unicode__(self):
        return self.idea

    @models.permalink
    def get_absolute_url(self):
        return "vote", [self.id]

    def my_tweet_text(self):
        params = {
            "hashtag": settings.SITE_THEME['HASHTAG'],
        }
        return _(
            u"Vote for my progressive idea for @ThinkBigUS #%s(hashtag)s. "
            "30 leaders in Congress will see top ideas!" % params)

    def tweet_text(self):
        text = settings.SITE_THEME['TWITTER_QUESTION_TEXT']
        if self.voter.twitter_handle:
            text += u" h/t @%s" % self.voter.twitter_handle
        return text

    def facebook_text(self):
        if len(self.idea) > 240:
            return self.idea[:240] + u'…'
        return self.idea

    def facebook_url(self):
        return u"https://www.facebook.com/sharer/sharer.php?&u=%(idea_url)s" % {
            "idea_url": quote_plus(self.really_absolute_url('fb')),
        }

    def reddit_url(self):
        return u"//www.reddit.com/submit?url=%s" % (quote_plus(
            self.really_absolute_url('reddit')), )

    def email_url(self):
        subject = settings.SITE_THEME['EMAIL_SUBJECT']
        body = settings.SITE_THEME['EMAIL_BODY'] % {
            "url": self.really_absolute_url('email'),
        }
        return u"mailto:?subject=%s&body=%s" % (urlquote(subject),
                                                urlquote(body))

    def sms_url(self):
        params = {
            "url": self.really_absolute_url('sms'),
            "hashtag": settings.SITE_THEME['HASHTAG'],
        }
        body = _(
            u"Vote for my progressive idea for @OpenDebaters #%(hashtag)s. %(url)s"
            % params)
        return u"sms:;?body=%s" % (quote_plus(body), )

    def really_absolute_url(self, source=None):
        url = settings.SITE_DOMAIN_WITH_PROTOCOL + self.get_absolute_url()
        if source is not None:
            url += '?source=share-%s-%s' % (source, self.id)
        return url

    def twitter_url(self):
        url_tmpl = u"https://twitter.com/intent/tweet?url=" + \
                   "%(idea_url)s&text=%(tweet_text)s"
        return url_tmpl % {
            "idea_url": quote_plus(self.really_absolute_url('tw')),
            "tweet_text": quote_plus(self.tweet_text()),
        }

    def twitter_title(self):
        # Vote on this question for the FL-Sen #OpenDebate!
        return settings.SITE_THEME['TWITTER_QUESTION_TITLE'].format(
            idea=self.idea)

    def twitter_description(self):
        # "{idea}" At 8pm EDT on 4/25, Jolly & Grayson answer top vote-getting questions at
        # bottom-up #OpenDebate hosted by [TBD], Open Debate Coalition, Progressive Change Institute
        return settings.SITE_THEME['TWITTER_QUESTION_DESCRIPTION'].format(
            idea=self.idea)

    def facebook_title(self):
        return settings.SITE_THEME['FACEBOOK_QUESTION_TITLE'].format(
            idea=self.idea)

    def facebook_description(self):
        return settings.SITE_THEME['FACEBOOK_QUESTION_DESCRIPTION'].format(
            idea=self.idea)
Ejemplo n.º 30
0
class Match(models.Model):
    """A match between two teams."""
    date = models.DateTimeField()
    league = models.ForeignKey(League, on_delete=models.CASCADE, null=True)
    matchday = models.IntegerField(default=0)
    team_home = models.ForeignKey(Team,
                                  related_name='+',
                                  on_delete=models.DO_NOTHING)
    team_visitor = models.ForeignKey(Team,
                                     related_name='+',
                                     on_delete=models.DO_NOTHING)
    round = models.CharField(default='1', max_length=64)
    location = models.CharField(max_length=128, null=True)
    score_home = models.IntegerField(default=0)
    score_visitor = models.IntegerField(default=0)
    wallet = models.ForeignKey("django_bitcoin.Wallet",
                               on_delete=models.DO_NOTHING)
    xmlsoccer_matchid = models.IntegerField()
    finished = models.BooleanField(default=False)
    updated = models.DateTimeField(default=timezone.now)
    timeinfo = models.TextField(null=True)
    content = models.TextField(null=True)

    #full text search
    search_index = VectorField()

    objects = SearchManager(fields=('content', ),
                            config='pg_catalog.english',
                            search_field='search_index',
                            auto_update_search_field=True)

    def has_started(self):
        return self.date <= timezone.now()

    def times(self):
        try:
            minutes = re.match('(\d+)', self.timeinfo)
            if minutes:
                minutes = minutes.group(0)
                return int(minutes) // 45 + 1
        except Exception:
            return None

    def __str__(self):
        return '%s %s - %s (%s %s)' % (
            self.date, self.team_home.name, self.team_visitor.name,
            self.league.country, self.league.league_name)

    def short(self):
        return '%s - %s' % (self.team_home.name, self.team_visitor.name)

    # this is not needed if small_image is created at set_image
    def save(self, *args, **kwargs):
        str_wallet = '%s-%s' % (self.team_home.handle,
                                self.team_visitor.handle)
        str_wallet = str_wallet[:45]
        self.wallet, created = Wallet.objects.get_or_create(label=str_wallet)
        self.content = self.__str__()
        super(Match, self).save(*args, **kwargs)
        # I write bets coefficients in table
        if MatchBet.objects.filter(match=self).count() == 0:
            for bet in BetType.objects.all():
                row = MatchBet(match=self,
                               bet=bet,
                               max_value=bet.max_value,
                               min_value=bet.min_value)
                row.save()

    def closeMatch(self):
        if self.finished == True:
            logger = logging.getLogger("Match__closeMatch")
            result = True
            logger.info("Закрывается матч: " + str(self))
            bank_profile = Profile.objects.filter(
                user__is_superuser=True).first()
            for tip in Tipp.objects.filter(match=self, state="In Game"):
                closed = tip.close(bank_profile.wallet)
                result &= closed
            try:
                if self.wallet.total_balance() > 0:
                    self.wallet.send_to_wallet(bank_profile.wallet,
                                               self.wallet.total_balance())
            except Wallet.DoesNotExist:
                logger.error("К матчу " + str(self) +
                             " не привязан кошелек! Проверьте работу bitcoind")
            return result
        return False

    #Coefficient bid for
    def getMainBets(self):
        bets = BetType.objects.filter(bet_group__is_main=True).all()
        return MatchBet.objects.filter(match=self).filter(
            bet__in=bets).order_by('bet__order').all()

    def getAllBets(self):
        return MatchBet.objects.filter(match=self).filter(
            models.Q(bet__bet_group__is_main=True)
            | models.Q(is_enabled=True)).order_by("bet__id").all()

    def total_balance(self):
        return self.wallet.total_balance()

    def needUpdateOdds(self):
        if MatchBet.objects.filter(match=self).filter(
                match__updated__lte=timezone.now() - timedelta(days=1)).filter(
                    match__date__lte=timezone.now() +
                    timedelta(days=14)).count() > 0 and self.league.is_enabled:
            return True
        return False

    def updateOdds(self):
        for bet in MatchBet.objects.filter(match=self).all():
            bet.calculate()
        self.updated = timezone.now()
        self.save()

    def isIntrestingOdds(self):
        if MatchBet.objects.filter(match=self).filter(score__gte=1.1).filter(
                bet__bet_group__is_main=True).count() == 3:
            return True
        return False