Exemplo n.º 1
0
    def handle_model(self):
        self.model.add_to_class('tags', TagField(_('tags')))

        # use another name for the tag descriptor See
        # http://code.google.com/p/django-tagging/issues/detail?id=95 for the
        # reason why
        tagging.register(self.model, tag_descriptor_attr='etags')
Exemplo n.º 2
0
    def handle_model(self):
        self.model.add_to_class('tags', TagField(_('tags')))

        # use another name for the tag descriptor See
        # http://code.google.com/p/django-tagging/issues/detail?id=95 for the
        # reason why
        tagging.register(self.model, tag_descriptor_attr='etags')
Exemplo n.º 3
0
def register(cls, admin_cls, *args):    
    TagField.help_text = _('Use commas to separate tags.')
    cls.add_to_class('tags', TagField(_('tags')))

    # use another name for the tag descriptor
    # See http://code.google.com/p/django-tagging/issues/detail?id=95 for the reason why
    tagging.register(cls, tag_descriptor_attr='etags')
    admin_cls.search_fields += ('tags',)
    admin_cls.show_on_top.append('tags')
Exemplo n.º 4
0
    def next_breakout_session(self):
        try:
            return self.future_breakout_sessions[0]
        except IndexError:
            return None
        
    
    def geocode(self):
        place, (self.latitude, self.longitude) = Venue.geocoder.geocode("%s, %s, %s %s" % (self.street_address_1, self.city, self.state, self.zip_code, ))
        return place
    
    class Meta:
        get_latest_by = 'updated_on'


tagging.register(Venue)

class BreakoutSessionFormat(models.Model):
    created_on = models.DateTimeField(auto_now_add=True)
    updated_on = models.DateTimeField(auto_now=True)
    name = models.CharField(max_length=50)    
    slug = models.SlugField(name='Short Name', unique=True)
    description = models.TextField(null=True, blank=True)
    order = models.PositiveSmallIntegerField(default=20, choices=((i, str(i)) for i in range(1, 40)))
    
    def __unicode__(self):
        return self.name
    
    @models.permalink
    def get_absolute_url(self):
        return ('upcoming_breakout_session_list', (), { 'session_format_slug': self.slug })
Exemplo n.º 5
0
    title = models.CharField(max_length=250)
    url = models.URLField('URL', unique=True)
    pub_date = models.DateTimeField(default=datetime.datetime.now)
    slug = models.SlugField(
        unique_for_date='pub_date',
        help_text='Must be unique for the publication date.')
    description = models.TextField(blank=True)
    description_html = models.TextField(editable=False, blank=True)
    tags = TagField(help_text=u'Seperate tags with spaces.')

    class Meta:
        ordering = ['-pub_date']

    def __unicode__(self):
        return self.title

    def save(self):
        if self.description:
            self.description_html = markdown(self.description)
        super(Link, self).save()

    # @models.permalink
    # def get_absolute_url(self):
    # 	return ('links_link_detail', (), { 'year': self.pub_date.strftime("%Y"),
    # 									   'month': self.pub_date.strftime("%b").lower(),
    # 									   'day': self.pub_date.strftime("%d"),
    # 									   'slug': self.slug })


tagging.register(Link, tag_descriptor_attr='etags')
Exemplo n.º 6
0
        verbose_name_plural = _("Posts")
        ordering = ('-date_created', '-date_modified')
        unique_together = (('feed', 'guid'),)

    def __str__(self):
        return "{} [{}]".format(self.title, self.feed.title)

    @models.permalink
    def get_absolute_url(self):
        return ('planet.views.post_detail', [str(self.id), self.get_slug()])

    def get_slug(self):
        return slugify(self.title) or "no-title"

# each Post object now will have got a .tags attribute!
register(Post)

# Deleting all asociated tags.
def delete_asociated_tags(sender, **kwargs):
    Tag.objects.update_tags(kwargs['instance'], None)
pre_delete.connect(delete_asociated_tags, sender=Post)


@python_2_unicode_compatible
class Author(models.Model):
    """
    An author is everyone who wrote or has contributed to write a post.
    """
    name = models.CharField(_("Name"), max_length=255, null=True,
        blank=True, db_index=True)
    email = models.EmailField(_("Author email"), blank=True, db_index=True)
Exemplo n.º 7
0
        return self.user.groups

    def save(self, *args, **kwargs):
        t_tags = ''
        """"""
        for tag in self.tags:
            t_tags += '%s, ' % tag

        self.tags = t_tags
        self.d_tags = t_tags[:1000]

        super(Profile, self).save(*args, **kwargs)


try:
    tagging.register(Profile)
except:
    pass

arating.enable_voting_on(Profile)


class Community(MigrationMixin):

    uuid = UUIDField(primary_key=False)
    name = models.CharField(max_length=200, db_index=True)
    slug = AutoSlugField(populate_from='name',
                         editable=True,
                         blank=True,
                         overwrite=True)
Exemplo n.º 8
0
    def upvotes(self):
        return self.votes.filter(vote_up=True).count()

    def downvotes(self):
        return self.votes.filter(vote_up=False).count()

    def allvotes(self):
        return self.votes.count()

    def voted(self, visitor_id):
        try:
            v = self.votes.get(visitor__pk=visitor_id)
            return 1 if v.vote_up else -1
        except ObjectDoesNotExist:
            return 0

class Vote(models.Model):
    visitor = models.ForeignKey(Session)
    post = models.ForeignKey(Post, related_name='votes')
    vote_up = models.BooleanField()

    created = models.DateTimeField(auto_now_add=True)
    modified = models.DateTimeField(auto_now=True)
    submitted_from = models.IPAddressField()

    class Meta:
        unique_together = (('visitor', 'post'),)

tagging.register(Post)
Exemplo n.º 9
0
        return self._next_previous_helper('next')
    
    def get_previous(self):
        """
        Returns the previous Entry with "live" status by ``pub_date``,
        if there is one, or ``None`` if there isn't.
        
        In public-facing templates, use this method instead of
        ``get_previous_by_pub_date``, because
        ``get_previous_by_pub_date`` does not differentiate entry
        status..
        
        """
        return self._next_previous_helper('previous')

    def _get_comment_count(self):
        model = settings.USE_FREE_COMMENTS and comment_models.FreeComment or comment_models.Comment
        ctype = ContentType.objects.get_for_model(self)
        return model.objects.filter(content_type__pk=ctype.id, object_id__exact=self.id).count()
    _get_comment_count.short_description = 'Number of comments'


class ColtraneModerator(CommentModerator):
    akismet = True
    auto_close_field = 'pub_date'
    email_notification = True
    enable_field = 'enable_comments'
    close_after = settings.COMMENTS_MODERATE_AFTER

tagging.register(Entry, 'tag_set')
Exemplo n.º 10
0
                        plc.save(force_update=True)
        return super(Publishable, self).save(**kwargs)

    def delete(self):
        url = self.get_absolute_url()
        Redirect.objects.filter(new_path=url).delete()
        return super(Publishable, self).delete()

    def __unicode__(self):
        return self.title


# FIXME find another way to register!
if 'tagging' in settings.INSTALLED_APPS:
    import tagging
    tagging.register(Publishable)


class Placement(models.Model):
    # listing's target - a Publishable object
    publishable = models.ForeignKey(Publishable,
                                    verbose_name=_('Publishable object'))
    category = models.ForeignKey(Category,
                                 verbose_name=_('Category'),
                                 db_index=True)
    publish_from = models.DateTimeField(
        _("Start of visibility"))  #, default=datetime.now)
    publish_to = models.DateTimeField(_("End of visibility"),
                                      null=True,
                                      blank=True)
    slug = models.SlugField(_('Slug'), max_length=255, blank=True)
Exemplo n.º 11
0
    @models.permalink
    def get_absolute_url(self):        
        if self.research_paper :
            return ('singlepaperurl',(),{'entry_id': self.id})
        else:
            return ('singleposturl',(),{'entry_id': self.id})
            
                
    def getfullurl(self,institute):
        ''' brings entire url with the domain name '''
        url =  "http://%s%s%s" %(institute.subdomain.strip(),settings.DOMAIN,self.get_absolute_url())
        return url


try :
    tagging.register(Entry)
except tagging.AlreadyRegistered :
    pass  
    
    
    
class Comment(models.Model):
    entry =  models.ForeignKey(Entry)
    text = models.TextField()
    createddate = models.DateTimeField(auto_now_add=True)
    updateddate = models.DateTimeField(auto_now=True)   
    user = models.ForeignKey(User,related_name="blogcomments",null=True,blank=True)
    nouser = models.BooleanField(default=False)
    username = models.CharField(max_length=56,null=True,blank=True)
    webaddress = models.CharField(max_length=1024,null=True,blank=True)
    
Exemplo n.º 12
0
    class Meta:
        ordering = ('-published', )

    def get_linecount(self):
        return len(self.content.splitlines())

    def content_splitted(self):
        return self.content_highlighted.splitlines()

    def save(self, *args, **kwargs):
        if not self.pk:
            self.published = datetime.datetime.now()
            self.secret_id = generate_secret_id()
        self.content_highlighted = pygmentize(self.content, self.lexer)
        super(Snippet, self).save(*args, **kwargs)

    @permalink
    def get_absolute_url(self):
        return ('snippet_details', (self.secret_id, ))

    def __unicode__(self):
        return '%s' % self.secret_id


mptt.register(Snippet, order_insertion_by=['content'])
try:
    tagging.register(Snippet)
except:
    pass
Exemplo n.º 13
0
from django.db import models

from tagging.fields import TagField
import tagging


class Taggable(models.Model):
    name = models.CharField(max_length=50)
    tags = TagField(null=True, blank=True)
    parent = models.ForeignKey('self', null=True, blank=True)

    def __unicode__(self):
        return self.name


tagging.register(Taggable, tag_descriptor_attr='etags')
Exemplo n.º 14
0
    def streams(self):
        return Stream.objects.filter(event=self)

    def update(self, data):
        if isinstance(data, basestring):
            data = json.loads(data)

        valid_fields = ["end", "tags"]

        for key, value in data.iteritems():
            if key in valid_fields:
                setattr(self, key, value)


tagging.register(Event, tag_descriptor_attr="tag_list")


class Attribute(models.Model):
    event = models.ForeignKey(Event)
    key = models.CharField(max_length=20)
    value = models.CharField(max_length=60)

    def __unicode__(self):
        return "Key: %s, Value: %s" % (self.key, self.value)


class Stream(models.Model):
    event = models.ForeignKey(Event)
    name = models.CharField(max_length=20)
    text = models.TextField(blank=True, null=True)
Exemplo n.º 15
0
class ActiveProductReviewManager(models.Manager):
    def all(self):
        return super(ActiveProductReviewManager, self).all() \
                                                    .filter(is_approved=True)

class ProductReview(models.Model):
    RATINGS = ((5,5),(4,4),(3,3),(2,2),(1,1),)
    product = models.ForeignKey(Product)
    user = models.ForeignKey(User)
    title = models.CharField(max_length=50)
    date = models.DateTimeField(auto_now_add=True)
    rating = models.PositiveSmallIntegerField(default=5, choices=RATINGS)
    is_approved = models.BooleanField(default=True)
    content = models.TextField()
    
    objects = models.Manager()
    approved = ActiveProductReviewManager()

import tagging
# Product model class definition here
try:
    tagging.register(Product)
except tagging.AlreadyRegistered:
    pass

post_save.connect(cache_update, sender=Product)
post_delete.connect(cache_evict, sender=Product)
post_save.connect(cache_update, sender=Category)
post_delete.connect(cache_evict, sender=Category)
Exemplo n.º 16
0
    @models.permalink
    def get_activation_absolute_url(self):
        return ('activationurl', (), {
            'userid': self.user.id,
            'activation_key': self.activation_key
        })

    def get_full_activation_url(self, institute):
        ''' brings entire url with the domain name '''
        url = "http://%s%s%s" % (institute.subdomain.strip(), settings.DOMAIN,
                                 self.get_activation_absolute_url())
        return url


try:
    tagging.register(UserProfile)
except tagging.AlreadyRegistered:
    pass


class Faculty(models.Model):
    institutes = models.ManyToManyField(Institution,
                                        through='FacultyInstitute')
    profile = models.ForeignKey(UserProfile, unique=True)
    createddate = models.DateTimeField(auto_now_add=True)
    updateddate = models.DateTimeField(auto_now=True)

    def __unicode__(self):
        return "Faculty Name = %s , email = %s" % (self.profile.user.username,
                                                   self.profile.user.email)
Exemplo n.º 17
0
        label='Sähköposti',
        widget=forms.TextInput(attrs={'size': '40'}),
        required=False,
        help_text="<span class='help_text'>Ei näytetä viestissä</note>")
    content = forms.CharField(label='Viesti',
                              widget=forms.Textarea(attrs={
                                  'cols': '60',
                                  'rows': '10'
                              }))
    tag_list = forms.CharField(label='Aiheet',
                               widget=forms.TextInput(attrs={'size': '40'}),
                               help_text='')
    #tag_list = forms.MultipleChoiceField(label="Aiheet", widget=forms.CheckboxSelectMultiple, choices={'A': 'A'})
    #tag_list = forms.TagField(widget=TagAutocomplete())

    #l = Entry.tag_list
    #return l

    #def clean_content(self):
    #    content = self.cleaned_data.get('username', '')
    #    if len(content) < 20:
    #         raise forms.ValidationError(u'Viestin on oltava vähintään ' + str(20) + ' merkin mittainen.')
    #    return content


#admin.site.register(Entry)
try:
    tagging.register(Entry)  # , tag_descriptor_attr='tags'
except tagging.AlreadyRegistered:
    pass
Exemplo n.º 18
0
    def get_absolute_url(self):
        """
        Converts job title into a named URL to get the job's absolute url.
        """
        return ("jobs_job", (self.slug,))

    @models.permalink
    def get_application_url(self):
        """
        Returns the url for this job's application site (i.e., the "apply now"
        link.
        """
        return ("jobs_application", (self.slug,))

try:
    tagging.register(Job)
except tagging.AlreadyRegistered:
    pass


class JobUser(models.Model):
    """
    Describes the adminstrative roles for any given job.
    Roles include admin (all access), and viewer (read only)
    """
    limit_permissions_to = {"codename__in": ["can_view","can_do"],
                            "content_type__name": "job user"}
    limit_users_to = {"is_staff": True}
    permission = models.ForeignKey(Permission, limit_choices_to=limit_permissions_to)
    user = models.ForeignKey(User, limit_choices_to=limit_users_to)
    job  = models.ForeignKey(Job)
Exemplo n.º 19
0
    tags = TagField(help_text=u'Seperate tags with spaces.')
    love_count = models.IntegerField(default=0)

    #	live = LiveEntryManager()
    #	objects = models.Manager()

    class Meta:
        ordering = ['-pub_date']
        verbose_name_plural = u'Entries'

    def __unicode__(self):
        return self.title

    def save(self, force_insert=False, force_update=False):
        self.body_html = markdown(self.body)
        self.excerpt_html = markdown(self.excerpt)
        super(Entry, self).save(force_insert, force_update)

    @models.permalink
    def get_absolute_url(self):
        return ('blog_entry_detail', (), {
            'year': self.pub_date.strftime("%Y"),
            'month': self.pub_date.strftime("%b").lower(),
            'day': self.pub_date.strftime("%d"),
            'slug': self.slug
        })


tagging.register(Entry, tag_descriptor_attr='etags')
Exemplo n.º 20
0
    def get_related_articles(self):
        most_similar = Article.tagged.with_all(
            self.tags).order_by('-publication_date')[:6]
        similar = Article.tagged.with_any(
            self.tags).order_by('-publication_date')[:11]
        related_articles = []
        for article in most_similar:
            related_articles.append(article)
        for article in similar:
            if not article in related_articles:
                related_articles.append(article)
        try:
            related_articles.remove(self)
        except ValueError:
            pass
        return related_articles[:5]

    @models.permalink
    def get_absolute_url(self):
        return ('article_show', (), {
            'channel': self.channel.slug,
            'slug': self.slug
        })


import tagging
try:
    tagging.register(Article)
except tagging.AlreadyRegistered:
    pass
Exemplo n.º 21
0
from django.db import models

from tagging.fields import TagField
import tagging


class OutsideAdmin(models.Model):
    name = models.CharField(max_length=200)
    parent = models.ForeignKey('self', null=True, blank=True)
    tags = TagField(null=True, blank=True)

    def __unicode__(self):
        return self.name


tagging.register(OutsideAdmin, tag_descriptor_attr='etags')
Exemplo n.º 22
0
            for tag in self.tags:
                t_tags += '%s, ' % tag

            self.tags = t_tags
            self.d_tags = t_tags
        except Exception, e:
            #print e
            pass

        # self.user = request.user
        super(Playlist, self).save(*args, **kwargs)


try:
    pass
    tagging.register(Playlist)
except:
    pass

arating.enable_voting_on(Playlist)


def playlist_post_save(sender, **kwargs):
    #obj = kwargs['instance']
    pass


post_save.connect(playlist_post_save, sender=Playlist)


class PlaylistMedia(models.Model):
Exemplo n.º 23
0
        return Problem.STATE_CHOICES[self.state][1]

    def was_solved_by(self, user):
        return Solver.objects.filter(problem=self, user=user,
                                     solved=True).exists()

    def get_absolute_url(self):
        return reverse("judge-problem-read", kwargs={"slug": self.slug})

    class Meta:
        permissions = (
            ('read_problem', 'Can read problem always'),
            ('edit_problem', 'Can edit problem always'),
        )

tagging.register(Problem)

class Attachment(models.Model):
    problem = models.ForeignKey(Problem, db_index=True)
    file = models.FileField(max_length=1024, upload_to='/will_not_be_used/')

class Submission(models.Model):
    (RECEIVED, COMPILING, RUNNING, JUDGING, COMPILE_ERROR,
    OK, ACCEPTED, WRONG_ANSWER, RUNTIME_ERROR, TIME_LIMIT_EXCEEDED,
    CANT_BE_JUDGED, REJUDGE_REQUESTED) = range(12)
    STATES_KOR = dict([(RECEIVED, u"수신"),
                       (COMPILING, u"컴파일중"),
                       (RUNNING, u"실행중"),
                       (JUDGING, u"채점중"),
                       (COMPILE_ERROR, u"컴파일 실패"),
                       (OK, u"수행완료"),
Exemplo n.º 24
0
                pass
            except TypeError:
                pass
        if self.cover == "":
            if book is None:
                book = utils.get_book_from_cache(str(self.douban_id))
            if book is None:
                return self.cover
            self.cover = book['link'][2]['@href']
            self.save()
        return self.cover.replace('spic', 'lpic')
    
    def available_bookownership(self):
        return self.bookownership_set.filter(~Q(status=u"5"))

tagging.register(Book)


class BookComment(models.Model):
    datetime = models.DateTimeField()
    book = models.ForeignKey(Book)
    user = models.ForeignKey(User)
    title = models.CharField(max_length=256)    
    content = models.CharField(max_length=2048)
    status = models.IntegerField()


BO_STAT = (
    ("1", "可借"),
    ("2", "不可借"),
    ("3", "借出"),
Exemplo n.º 25
0
    forma_pagamento = models.ForeignKey(FormaPagamento, verbose_name=u'Pagamento')
    pago = models.BooleanField(default=True)

    class Meta:
        ordering = ['vencimento',]

    def __unicode__(self):
        return self.desc

    def save(self, **kwargs):
        if self.tipo == 'D':
            if self.valor > 0:
                self.valor = -self.valor
        else:
            if self.valor < 0:
                self.valor = -self.valor

        super(Lancamento, self).save()

"""
Utiliza a app plugável Tagging com o model Lancamento.
"""
import tagging
tagging.register(Lancamento)


    
    


Exemplo n.º 26
0
                data[item.key] = item.value
        return data

    def streams(self):
        return Stream.objects.filter(event=self)

    def update(self, data):
        if isinstance(data, basestring):
            data = json.loads(data)

        valid_fields = ["end", "tags"]

        for key, value in data.iteritems():
            if key in valid_fields:
                setattr(self, key, value)
tagging.register(Event, tag_descriptor_attr="tag_list")


class Attribute(models.Model):
    event = models.ForeignKey(Event)
    key = models.CharField(max_length=20)
    value = models.CharField(max_length=60)

    def __unicode__(self):
        return "Key: %s, Value: %s" % (self.key, self.value)


class Stream(models.Model):
    event = models.ForeignKey(Event)
    name = models.CharField(max_length=20)
    text = models.TextField(blank=True, null=True)
Exemplo n.º 27
0
    class Meta:
        verbose_name = _("Post")
        verbose_name_plural = _("Posts")
        ordering = ('-date_created', '-date_modified')
        unique_together = (('feed', 'guid'), )

    def __unicode__(self):
        return u"%s [%s]" % (self.title, self.feed.title)

    @models.permalink
    def get_absolute_url(self):
        return ('planet.views.post_detail', [str(self.id)])


# each Post object now will have got a .tags attribute!
tagging.register(Post)


# Deleting all asociated tags.
def delete_asociated_tags(sender, **kwargs):
    Tag.objects.update_tags(kwargs['instance'], None)


pre_delete.connect(delete_asociated_tags, sender=Post)


class Author(models.Model):
    """
    An author is everyone who wrote or has contributed to write a post.
    """
    name = models.CharField(_("Name"),
Exemplo n.º 28
0
from django.db import models

from tagging.fields import TagField
import tagging


class Taggable(models.Model):
	name = models.CharField(max_length=50)
	tags = TagField(null=True, blank=True)

	def __unicode__(self):
		return self.name

tagging.register(Taggable, tag_descriptor_attr='etags')
Exemplo n.º 29
0
        profile.show_count = self.user.show_set.count()

        profile.save()
        return self

    def delete(self, *args, **kwargs):
        super(Show, self).delete(*args, **kwargs)
        profile = self.user.get_profile()
        profile.like_count = self.user.likes.count()
        profile.show_count = self.user.show_set.count()
        profile.save()

    class Meta:
        ordering = ["-dtcreated"]

tagging.register(Show)

def increase_photo_comment_count(sender, instance, signal, **kwargs):
    if instance.content_type.model_class() == Show:
        photo = Show.objects.get(pk=instance.object_id)
        photo.comment_count = F("comment_count") + 1
        photo.save()

def decrease_photo_comment_count(sender, instance, signal, **kwargs):
    if instance.content_type.model_class() == Show:
        photo = Show.objects.get(pk=instance.object_id)
        photo.comment_count = F("comment_count") - 1
        photo.save()

models.signals.post_save.connect(increase_photo_comment_count, sender=Comment)
models.signals.post_delete.connect(decrease_photo_comment_count, sender=Comment)
Exemplo n.º 30
0
    def save(self, *args, **kwargs):
        fusion = super(FusionForm, self).save(*args, **kwargs)
        logging.info("Saved fusion " + str(fusion.id) + " by " +
                     fusion.user.username)

        if len(fusion.points) > 4:
            fusion.align()

        Tag.objects.update_tags(
            fusion, ','.join([tag.name for tag in fusion.then.tags] +
                             extract_words(fusion.now.description)))
        fusion.save()
        return fusion


try:
    tagging.register(ImageType)
except tagging.AlreadyRegistered:
    pass

try:
    tagging.register(Image)
except tagging.AlreadyRegistered:
    pass

try:
    tagging.register(Fusion)
except tagging.AlreadyRegistered:
    pass
Exemplo n.º 31
0
import tagging
from models import Project

try:
    tagging.register(Project)
except tagging.AlreadyRegistered:
    pass
Exemplo n.º 32
0
        conference = None
        x = re.match(r'^([^:]+):(.*)$', t.title)
        if x:
            conference=x.groups()[0].strip()
            t.title=x.groups()[1].strip()

        """ speakers, "title" """
        x = re.match(r'^([^"]+)"([^"]+)"$', t.title)
        if x:
            name_match = x.groups()[0].strip().split(',')
            name = name_match[0].strip()
            job_title = name_match[1].strip() if len(name_match)>1 else ''
            t.save()
            for namestr in name.split(' and '):
                ss, created = Speaker.objects.get_or_create(name=namestr, title=job_title)
                t.speakers.add(ss)
            t.title=x.groups()[1]
        if conference:
            t.title+=' (%s)' % conference
        return t

class TalkFeature(models.Model):
    talk            = models.ForeignKey(Talk)
    date            = models.DateField(default=datetime.today)

    def __unicode__(self):
        return u'%s on %s' % (self.date, self.talk.title,)


tagging.register(Talk)
        """
        Returns a list of the primary keys of the User objects that this Video has VideoSession objects for.
        """

        user_keys_list = facade.models.User.objects.filter(
            assignments__task__id__exact=self.id).values_list('id', flat=True)
        # Let's use a set to make this list unique
        user_keys_set = set(user_keys_list)
        return list(user_keys_set)

    #: A list of primary keys of User objects that have watched this Video
    users_who_watched = property(_get_users_who_watched)


try:
    tagging.register(Video)
except tagging.AlreadyRegistered:
    pass


class Category(pr_models.PRModel):
    name = models.CharField(max_length=31, null=False)
    managers = models.ManyToManyField(pr_models.User,
                                      related_name='categories')
    authorized_groups = models.ManyToManyField(pr_models.Group,
                                               related_name='categories')
    locked = pr_models.PRBooleanField(default=False)

    @property
    def approved_videos(self):
        approved = filter(lambda cr: cr.status == 'approved',
Exemplo n.º 34
0
        if(self.parent.album.highlight is not None and
           self.parent.album.highlight.id == self.id):
            self.parent.highlight = self.get_next()
            self.parent.save()
            
        tasks.albumitem_delete_directory.delay(self.get_directory())

        return super(AlbumConvertableItem, self).delete()

    def __unicode__(self):
        return self.title

    def get_tags(self):
        return tagging.models.Tag.objects.get_for_object(self)

tagging.register(AlbumConvertableItem, tag_descriptor_attr='tagss')

class Image(AlbumConvertableItem):
    pass
signals.pre_save.connect(albumitem_save, sender=Image)

def generate_image_thumbs(sender, instance, **kwargs):
    if(kwargs['created']):
        tasks.albumitem_generate_thumbnails.delay(instance, settings.ALBUMS_THUMBSIZES)
signals.post_save.connect(generate_image_thumbs, sender=Image)

class Video(AlbumConvertableItem):
    def get_video_path(self, filename):
        return os.path.join(self.get_directory(), filename)
    video = models.FileField(upload_to=get_video_path)
    video_ready = models.BooleanField(default=False, null=False)
Exemplo n.º 35
0
            self.category.save()
        if self.public_category:
            self.public_category.article_count = F("article_count") + 1
            self.public_category.save()
            #self.category.article_count += 1
            #self.category.save()
        super(Article, self).save(*args, **kwargs)

    def __unicode__(self):
        return self.title

    class Meta:
        verbose_name = u"文章"
        verbose_name_plural = u"文章"

tagging.register(Article)

class Attachment(models.Model):
    """文章附件"""
    article = models.ForeignKey("Article", verbose_name=u"文章", null=True, blank=True)
    user = models.ForeignKey(User, verbose_name=u"帐号")
    file = models.FileField(upload_to="uploads/article/attachment/%Y/%m/%d", verbose_name=u"附件")
    dtuploaded = models.DateTimeField(auto_now_add=True, verbose_name=u"上传日期")

    def file_basename(self):
        from os.path import basename
        return basename(self.file.name)

    def __unicode__(self):
        print dir(self.file)
        return self.file.name
Exemplo n.º 36
0
from django.contrib.auth.models import User
from django.db import models

import tagging


class Widget(models.Model):
    name = models.CharField(max_length=50)
    user = models.ForeignKey(User)

tagging.register(Widget)
Exemplo n.º 37
0
    rtype = models.ForeignKey(ResourceType, verbose_name="Resource Type", blank=True, null=True)
    
    def __unicode__(self):
        return '%s' % self.url
    
    def get_absolute_url(self):
        return '/resources/%s' % self.id
        
        
class PersonalResource(models.Model):
    added = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
    title = models.CharField(max_length=140, blank=True)
    note = models.TextField(blank=True)
    resource = models.ForeignKey('aresource.Resource')
    person = models.ForeignKey('people.Person')
    video = models.BooleanField()
    rtype = models.ForeignKey('aresource.ResourceType',verbose_name="Resource Type", blank=True, null=True)
    tag = TagField()
    
    def __unicode__(self):
        return self.resource
        
    def get_absolute_url(self):
        return '/people/user-resources/%s/%s' % (self.person.user, self.pk)
        
        


tagging.register(PersonalResource)
Exemplo n.º 38
0
        return u"%s" % self.name

    def save(self, *args, **kwargs):
        t_tags = ''
        """"""
        for tag in self.tags:
            t_tags += '%s, ' % tag

        self.tags = t_tags
        self.d_tags = t_tags[:245]

        super(Community, self).save(*args, **kwargs)


try:
    tagging.register(Community)
except:
    pass

arating.enable_voting_on(Community)


def create_profile(sender, instance, created, **kwargs):

    if kwargs['raw']:
        return

    if created:
        profile, created = Profile.objects.get_or_create(user=instance)

        default_group, created = Group.objects.get_or_create(
Exemplo n.º 39
0
        except ObjectDoesNotExist:
            msg = "PageMediaObject, not populated yet"

        return msg


class StoryLibrary(models.Model):
    """
    StoryLibrary is meant to be a personal subset of all story objects. 
    These are the story items that a user wants to keep in their own 
    library for easy access, and can be either published or unpublished. 
    """
    user = models.ForeignKey(User)
    stories = models.ManyToManyField(Story)


try:
    tagging.register(Story)
except tagging.AlreadyRegistered:
    pass


class StoryDownload(models.Model):
    '''
    used to track story downloads, for metrics and whatnot
    '''
    story = models.ForeignKey(Story)
    user = models.ForeignKey(User, null=True)
    device_id = models.CharField(max_length=20)
    download_time = models.DateTimeField(auto_now_add=True)
Exemplo n.º 40
0
      self.metering_mode      = smart_unicode(tags.get('EXIF MeteringMode', '')).strip() 
      self.focal_length       = smart_unicode(tags.get('EXIF FocalLength', '')).strip() 
      self.color_space        = smart_unicode(tags.get('EXIF ColorSpace', '')).strip()
      self.focal_length       = smart_unicode(tags.get('EXIF FocalLength', '')).strip()
      self.ycbcr_positioning  = smart_unicode(tags.get('Image YCbCrPositioning', '')).strip()
      self.sensing_method     = smart_unicode(tags.get('EXIF SensingMethod', '')).strip()
      
      if not self.date_created:
          if self.date_raw:
              self.date_created = self.date_raw

    class Meta:
        ordering = ['-date_created']
        get_latest_by = 'date_created'

tagging.register(Photo, tag_descriptor_attr='_tags')

class FlickrPhoto(models.Model):
  """A FlickrPhoto object hangs on top of a Photo object to add Flickr-specific metadata."""
  photo               = models.ForeignKey(Photo)
  flickr_photo_id     = models.CharField(max_length=200)
  secret              = models.CharField(max_length=30)
  server              = models.PositiveSmallIntegerField()
  isfavorite          = models.BooleanField(blank=True, default=False)
  license             = models.IntegerField()
  rotation            = models.IntegerField()
  originalsecret      = models.CharField(max_length=30, blank=True)
  originalformat      = models.CharField(max_length=100)
  media               = models.CharField(max_length=200)
  owner               = models.ForeignKey('FlickrUser')
  ispublic            = models.BooleanField(default=True)
Exemplo n.º 41
0
        """
        from ecomstore.checkout.models import Order, OrderItem
        from django.db.models import Q
        orders = Order.objects.filter(orderitem__product=self)
        users = User.objects.filter(order__orderitem__product=self)
        items = OrderItem.objects.filter( Q(order__in=orders) | 
                      Q(order__user__in=users) 
                      ).exclude(product=self)
        products = Product.active.filter(orderitem__in=items).distinct()
        return products
    
    @property
    def cache_key(self):
        return self.get_absolute_url()
try:
    tagging.register(Product)
except tagging.AlreadyRegistered:
    pass
    
class ActiveProductReviewManager(models.Manager):
    """ Manager class to return only those product reviews where each instance is approved """
    def all(self):
        return super(ActiveProductReviewManager, self).all().filter(is_approved=True)
        
class ProductReview(models.Model):
    """ model class containing product review data associated with a product instance """
    RATINGS = ((5,5),(4,4),(3,3),(2,2),(1,1),)
    
    product = models.ForeignKey(Product)
    user = models.ForeignKey(User)
    title = models.CharField(max_length=50)
Exemplo n.º 42
0
        if len(tags) == 0:
            return self.cleaned_data['tags']

        #if he enters any things make sure it contains only alpha numeric characters
        e = re.compile(r"[0-9A-Za-z-. ]+", re.IGNORECASE)
        result = e.match(tags)
        if result is not None and len(tags) == result.span()[1]:
            return self.cleaned_data['tags']
        else:
            raise forms.ValidationError(
                "Error:Tags should only contain alphanumeric characters, space,hypen('-'),dot('.'). Tags shoud be saperated by space"
            )


try:
    tagging.register(Event)
except tagging.AlreadyRegistered:
    pass


class EventAttendance(models.Model):
    ''' An entry here represents user is attending the event'''
    user = models.ForeignKey(User)
    event = models.ForeignKey(Event)
    institute = models.ForeignKey(Institution)
    createddate = models.DateTimeField(auto_now_add=True)
    updateddate = models.DateTimeField(auto_now=True)

    def __unicode__(self):
        return "User %s is attending the event %s" % (
            self.user.get_profile().fullname, self.event.what)
Exemplo n.º 43
0
    
    text = models.TextField()

    verbose_name = _("Text Collaboration")
    verbose_name_plural = _("Text Collaborations")

    class Meta:
        abstract = False
    
    def __unicode__(self):
        return unicode(self.text)

    @models.permalink
    def get_absolute_url(self):
        return ("textcontent_details_id", [str(self.id)])
tagging.register(TextContent)

class AudioContent(Content):

    """
    Content with sound
    """

    file = models.FileField(storage=_FILE_STORAGE, upload_to="audio/%Y/%m/%d")

    verbose_name = _("Audio Collaboration")
    verbose_name_plural = _("Audio Collaborations")

    class Meta:
        abstract = False
Exemplo n.º 44
0
        if self.auto_sync:
            self.need_sync = True
        super(SoftwareCollection, self).save(*args, **kwargs)

    def delete(self, *args, **kwargs):
        # rename of repos root is faster than deleting
        # (name can not start with '.', therefore this is save)
        os.rename(self.get_repos_root(), os.path.join(
            settings.REPOS_ROOT,
            self.maintainer.username,
            '.{}.deleted'.format(self.id)
        ))
        # delete scl in the database
        super(SoftwareCollection, self).delete(*args, **kwargs)

tagging.register(SoftwareCollection)


class Repo(models.Model):
    # automatic value (scl.slug/name) used as unique key
    slug            = models.SlugField(max_length=150, editable=False)
    scl             = models.ForeignKey(SoftwareCollection, related_name='repos')
    name            = models.CharField(_('Name'), max_length=50)
    copr_url        = models.CharField(_('Copr URL'), max_length=200)
    download_count  = models.IntegerField(default=0, editable=False)
    enabled         = models.BooleanField(_('Enabled'), default=True)

    class Meta:
        # in fact, since slug is made of those and slug is unique,
        # this is not necessarry, but as a side effect, it create index,
        # which may be useful
Exemplo n.º 45
0
	class Meta:
		verbose_name_plural = "Entries"
		ordering = ['-pub_date']

	def __unicode__(self):
		return self.title

	def get_absolute_url(self):
		return ('coltrane_entry_detail', (), {'year': self.pub_date.strftime("%Y"),
											   'month': self.pub_date.strftime("%b").lower(),
											   'day': self.pub_date.strftime("%d"),
											   'slug': self.slug })
	get_absolute_url = models.permalink(get_absolute_url)

tagging.register(Entry, tag_descriptor_attr='etags')

class Link(models.Model):
	title = models.CharField(max_length = 250)
	description = models.TextField(blank = True)
	description_html = models.TextField(blank = True)
	url = models.URLField(unique = True)
	posted_by = models.ForeignKey(User)
	pub_date = models.DateTimeField(default = datetime.datetime.now)
	slug = models.SlugField(unique_for_date = 'pub_date')
	tags = TagField()
	enable_comments = models.BooleanField(default = True)
	post_elsewhere = models.BooleanField('Post to Delicious', default = True)
	via_name = models.CharField('Via', max_length = 250, blank = True, help_text = 'The name of the person whose site you spotted the link on.  Optional.')
	via_url = models.URLField('Via URL', blank = True, help_text = 'The URL of the site where you spotted the link')
Exemplo n.º 46
0
        self.country.save()
        if self.region:
            self.region.num_people = self.region.djangoperson_set.count()
            self.region.save()

    class Meta:
        verbose_name = _('Django person')
        verbose_name_plural = _('Django people')

    def irc_tracking_allowed(self):
        return not self.machinetags.filter(
            namespace='privacy', predicate='irctrack', value='private',
        ).count()

tagging.register(DjangoPerson,
    tag_descriptor_attr='skilltags',
    tagged_item_manager_attr='skilltagged',
)


class PortfolioSite(models.Model):
    title = models.CharField(_('Title'), max_length=100)
    url = models.URLField(_('URL'), max_length=255)
    contributor = models.ForeignKey(DjangoPerson,
                                    verbose_name=_('Contributor'))

    def __unicode__(self):
        return u'%s <%s>' % (self.title, self.url)

    class Meta:
        verbose_name = _('Portfolio site')
        verbose_name_plural = _('Portfolio sites')
Exemplo n.º 47
0
        else:
            return reverse(
                'article_detail',
                args=[self.article_category, self.permalink, self.id])

    def get_files(self):
        files = []
        if self.files:
            files = [
                settings.MEDIA_URL + path for path in self.files.split('\n')
            ]

        return files


tagging.register(News, tag_descriptor_attr='tag_set')


class Event(CommonCms):

    #organization = models.ForeignKey(Organization, related_name='event_organization', null=True, blank=True)
    location = models.TextField(null=True, blank=True)
    start_date = models.DateField(null=True, blank=True, default=timezone.now)
    end_date = models.DateField(null=True, blank=True)
    time = models.CharField(max_length=255, null=True, blank=True)
    phone = models.TextField(null=True, blank=True)
    email = models.EmailField(max_length=255, null=True, blank=True)

    tags = TagAutocompleteTagItField(max_tags=False,
                                     null=True,
                                     blank=True,
Exemplo n.º 48
0
        return Problem.STATE_CHOICES[self.state][1]

    def was_solved_by(self, user):
        return Solver.objects.filter(problem=self, user=user,
                                     solved=True).exists()

    def get_absolute_url(self):
        return reverse("judge-problem-read", kwargs={"slug": self.slug})

    class Meta:
        permissions = (
            ('read_problem', 'Can read problem always'),
            ('edit_problem', 'Can edit problem always'),
        )

tagging.register(Problem)

class Attachment(models.Model):
    problem = models.ForeignKey(Problem, db_index=True)
    file = models.FileField(max_length=1024, upload_to='/will_not_be_used/')

class Submission(models.Model):
    (RECEIVED, COMPILING, RUNNING, JUDGING, COMPILE_ERROR,
    OK, ACCEPTED, WRONG_ANSWER, RUNTIME_ERROR, TIME_LIMIT_EXCEEDED,
    CANT_BE_JUDGED, REJUDGE_REQUESTED) = range(12)
    STATES_KOR = dict([(RECEIVED, u"수신"),
                       (COMPILING, u"컴파일중"),
                       (RUNNING, u"실행중"),
                       (JUDGING, u"채점중"),
                       (COMPILE_ERROR, u"컴파일 실패"),
                       (OK, u"수행완료"),
Exemplo n.º 49
0
# Create your models here.
class Link(models.Model):
	title = models.CharField(max_length=250)
	url = models.URLField('URL', unique=True)
	pub_date = models.DateTimeField(default=datetime.datetime.now)
	slug = models.SlugField(unique_for_date='pub_date', 
		help_text='Must be unique for the publication date.')
	description = models.TextField(blank=True)
	description_html = models.TextField(editable=False, blank=True)
	tags = TagField(help_text=u'Seperate tags with spaces.')

	class Meta:
		ordering = ['-pub_date']

	def __unicode__(self):
		return self.title

	def save(self):
		if self.description:
			self.description_html = markdown(self.description)
		super(Link, self).save()

	# @models.permalink
	# def get_absolute_url(self):
	# 	return ('links_link_detail', (), { 'year': self.pub_date.strftime("%Y"),
	# 									   'month': self.pub_date.strftime("%b").lower(),
	# 									   'day': self.pub_date.strftime("%d"),
	# 									   'slug': self.slug })
    
tagging.register(Link, tag_descriptor_attr='etags')
Exemplo n.º 50
0
# THIS MODEL IS DEPRECATED AND WILL BE REMOVED IN FUTURE VERSIONS.
class TextBook(models.Model):
    """THIS MODEL IS DEPRECATED AND WILL BE REMOVED IN FUTURE VERSIONS
    SINCE THIS MODEL IS A MERE COPY OF Task MODEL.
    Whatever this model tries to do can be done on views side thereby
    keeping our database as normalized as possible avoiding redundancies.
    """

    name = models.CharField(max_length=1024)

    chapters = models.ManyToManyField(Task, related_name="textbooks")

    tags_field = TagField(verbose_name="Tags")

    created_by = models.ForeignKey(User, related_name="created_textbooks")

    approved_by = models.ForeignKey(User, null=True, blank=True, related_name="approved_textbooks")

    status = models.CharField(max_length=255, choices=TB_STATUS_CHOICES, default="Unpublished")

    creation_datetime = models.DateTimeField(auto_now_add=True)

    approval_datetime = models.DateTimeField(blank=True, null=True)

    last_modified = models.DateTimeField(auto_now=True, default=datetime.now())


tagging.register(Task)
tagging.register(TextBook)
Exemplo n.º 51
0
            entryDetails)

        print "Publishing %s" % self.id
        print atomxml

        try:
            # TODO: don't resend this, split off on the other end after parsing once!
            idavoll.publish('user/%s' % username, str(self.id), atomxml)
            for follower in self.owner.followers.all():
                idavoll.publish('feed/%s' % follower.user.username,
                                str(self.id), atomxml)
                if follower.jid:
                    idavoll.message(follower.jid, unicode(message))
            for tag in self.tags:
                idavoll.publish('tag/%s' % tag.name, str(self.id), atomxml)
        except xmlrpclib.Fault, f:
            print "publishing entry %s: %s" % (self.id, f)
            #ignore

    def __unicode__(self):
        return u'%s says "%s" on %s' % (self.owner.user.username, self.content,
                                        self.post_date)

    class Meta(object):
        verbose_name_plural = "entries"
        ordering = ['-post_date']
        get_latest_by = 'post_date'


tagging.register(Entry)
Exemplo n.º 52
0
    # Denormalized data - for sort order
    offensiveness = models.IntegerField(default=0)
    score = models.IntegerField(default=0)
    hotness = models.IntegerField(default=0)
    votes = models.IntegerField(default=0)
    
    objects = IssueManager()
    active = ActiveManager()
    laws =  LawManager()

    def __unicode__(self):
        return self.title
       

tagging.register(Issue)


class IssueAdmin(admin.ModelAdmin):
    prepopulated_fields = {'slug' : ("title",)} 

    date_hierarchy = "time_stamp"
    list_display = ('title', 'time_stamp', 'user', 'is_draft' ) 
    list_filter = ('title', 'time_stamp', 'user', 'is_draft' )

    def votes(self , obj):
        return Vote.objects.get_for_object(obj).count()


admin.site.register(Issue, IssueAdmin)
Exemplo n.º 53
0
        
    def get_technologies(self):
        return self.technologies.all()

    def get_saved_by(self):
        from accounts.models import RhizomeUser
        return RhizomeUser.objects \
            .filter(saved_artworks__id = self.id) \
            .filter(is_active = True) \
            .filter(visible=True)
        
    def get_collection_fragment_url(self):
        return "/artbase/collections/artwork/%s/fragment.html" % self.id
                    
try:
    tagging.register(ArtworkStub,tag_descriptor_attr="artwork_stub")
except tagging.AlreadyRegistered:
    # http://code.google.com/p/django-tagging/issues/detail?id=128 
    # Not sure the right way to register a model for tagging b/c it
    # raises this error if registered more than once. We end up registering
    # the first time during "manage.py syncdb" and then a second time when
    # actually attempting to run the site.
    pass

def on_stub_save(sender, **kwargs):
    #
    # happens whenever someone saves, this could be refined to work with status changes instead
    #
    instance = kwargs['instance']
    if instance.status != "unsubmitted" or instance.status != "deleted":
        instance.user.get_profile().add_points_for_object(instance)
Exemplo n.º 54
0
            is_new = True
        else:
            is_new = False
        super(Project, self).save(*args, **kwargs)
        if is_new:
            project_created.send(sender=self)

    def delete(self, *args, **kwargs):
        self.resources.all().delete()
        project_deleted.send(sender=self)
        super(Project, self).delete(*args, **kwargs)

    @permalink
    def get_absolute_url(self):
        return ('project_detail', None, { 'project_slug': self.slug })

    @property
    def wordcount(self):
        return self.resources.aggregate(Sum('wordcount'))['wordcount__sum']

    @property
    def team_member_count(self):
        return len(User.objects.filter(team_members__project=self))

try:
    tagging.register(Project, tag_descriptor_attr='tagsobj')
except tagging.AlreadyRegistered, e:
    logger.debug('Tagging: %s' % str(e))

log_model(Project)
Exemplo n.º 55
0
            ad_m = ad.month
            ad_d = ad.day
            if ad_m == 0:
                ad_m = 1        
            if ad_d == 0:
                ad_d = 1
            
            rd = datetime.strptime('%s/%s/%s' % (ad_y, ad_m, ad_d), '%Y/%m/%d')
            self.releasedate = rd
        except:
            self.releasedate = None
        
        super(Release, self).save(*args, **kwargs)

try:
    tagging.register(Release)
except:
    pass


arating.enable_voting_on(Release)
post_save.connect(library_post_save, sender=Release)  


""""""
from actstream import action
def action_handler(sender, instance, created, **kwargs):
    try:
        verb = _('updated')
        if created:
            verb = _('created')
Exemplo n.º 56
0
                             null=True,
                             related_name='builds')
    extra_info = JSONField()

    class Meta:
        ordering = ['-finished']

    def __unicode__(self):
        return u"Build %s for %s" % (self.pk, self.project)

    @models.permalink
    def get_absolute_url(self):
        return ('build_detail', [self.project.slug, self.pk])


tagging.register(Build)


class BuildStep(models.Model):
    build = models.ForeignKey(Build, related_name='steps')
    success = models.BooleanField()
    started = models.DateTimeField()
    finished = models.DateTimeField()
    name = models.CharField(max_length=250)
    output = models.TextField(blank=True)
    errout = models.TextField(blank=True)
    extra_info = JSONField()

    class Meta:
        ordering = ['build', 'started']