Exemplo n.º 1
0
 def get_absolute_url(self):
     try:
         from django.db.models import permalink
         return permalink('simpletext_detail_view_name', [str(self.id)])
     except ImportError:
         from django.urls import reverse
         return reverse('simpletext_detail_view_name', args=[str(self.id)])
Exemplo n.º 2
0
def register(cls, admin_cls):
    cls.add_to_class('category', models.ForeignKey('articles.Category', verbose_name=_('category')))

    cls._meta.unique_together += [('category', 'slug')]

    @classmethod
    def get_urlpatterns(cls):
        from articles.modules.category import views

        return patterns('',
                        url(r'^(?P<category_url>[a-z0-9_/-]+/)articles/(?P<slug>[a-z0-9_-]+)/$',
                            views.CategoryArticleDetail.as_view(), name="article_detail"),
                        url(r'^(?P<category_url>[a-z0-9_/-]+/)articles/$', views.CategoryArticleList.as_view(),
                            name='article_category'),
                        url(r'^$', views.CategoryArticleList.as_view(), name='article_index'),
        )

    cls.get_urlpatterns = get_urlpatterns

    def get_absolute_url(self):
        return ('article_detail', (), {
                'category_url': self.category.local_url,
                'slug': self.slug,
                })
    cls.get_absolute_url = models.permalink(get_absolute_url)

    if admin_cls:
        admin_cls.add_extension_options('category')
Exemplo n.º 3
0
    def __init__(self, model, **kwargs):
        self.model = model
        for k, v in kwargs.items():
            setattr(self, k, v)

        if not hasattr(self.model, 'get_absolute_url'):
            # Add a simple primary key based URL to the model if it does not have one yet
            info = self.model._meta.app_label, self.model._meta.module_name
            self.model.get_absolute_url = models.permalink(lambda self: (
                '%s_%s_detail' % info, (self.pk,), {}))
Exemplo n.º 4
0
    def __init__(self, model, **kwargs):
        self.model = model
        for key, value in kwargs.items():
            if not hasattr(self, key):
                raise TypeError('%s() received an invalid keyword %r' % (
                    self.__class__.__name__, key))
            setattr(self, key, value)

        if not hasattr(self.model, 'get_absolute_url'):
            # Add a simple primary key based URL to the model if it does not have one yet
            info = self.model._meta.app_label, self.model._meta.module_name
            self.model.get_absolute_url = models.permalink(lambda self: (
                '%s_%s_detail' % info, (self.pk,), {}))
Exemplo n.º 5
0
class Notice(models.Model):
    recipient = models.ForeignKey(USER_MODEL,
                                  related_name="recieved_notices",
                                  verbose_name=_("recipient"))
    sender = models.ForeignKey(USER_MODEL,
                               null=True,
                               related_name="sent_notices",
                               verbose_name=_("sender"))
    message = models.TextField(_('message'))
    notice_type = models.ForeignKey(NoticeType, verbose_name=_('notice type'))
    added = models.DateTimeField(_('added'), auto_now_add=True)
    unseen = models.BooleanField(_('unseen'), default=True)
    archived = models.BooleanField(_('archived'), default=False)
    on_site = models.BooleanField(_('on site'))
    related_object_id = models.IntegerField(_('related object'), null=True)

    objects = NoticeManager()

    def __unicode__(self):
        return self.message

    def archive(self):
        self.archived = True
        self.save()

    def is_unseen(self):
        """
        returns value of self.unseen but also changes it to false.

        Use this in a template to mark an unseen notice differently the first
        time it is shown.
        """
        unseen = self.unseen
        if unseen:
            self.unseen = False
            self.save()
        return unseen

    class Meta:
        ordering = ["-added"]
        verbose_name = _("notice")
        verbose_name_plural = _("notices")

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

    def get_absolute_url(self):
        return ("notification_notice", [str(self.pk)])

    get_absolute_url = models.permalink(get_absolute_url)
Exemplo n.º 6
0
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 spottedthelinkon.Optional.')
    via_url = models.URLField(
        'Via URL',
        blank=True,
        help_text='The URL of the site where you spotted the link.Optional.')

    class Meta:
        ordering = ['-pub_date']

    def __unicode__(self):
        return self.title

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

        if not self.id and self.post_elsewhere:
            import pydelicious
            from django.utils.encoding import smart_str
            pydelicious.add(settings.DELICIOUS_USER,
                            settings.DELICIOUS_PASSWORD, smart_str(self.url),
                            smart_str(self.title), smart_str(self.tags))
        super(Link, self).save()

    def get_absolute_url(self):
        return ('wolf_link_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)
Exemplo n.º 7
0
class Brand(models.Model, TranslatedObjectMixin):
    """A product brand"""
    site = models.ForeignKey(Site)
    slug = models.SlugField(_("Slug"),
                            unique=True,
                            help_text=_("Used for URLs"))
    products = models.ManyToManyField(Product,
                                      blank=True,
                                      verbose_name=_("Products"),
                                      through='BrandProduct')
    ordering = models.IntegerField(_("Ordering"))
    active = models.BooleanField(default=True)

    objects = BrandManager()

    def _active_categories(self):
        return [cat for cat in self.categories.all() if cat.has_content()]

    active_categories = property(fget=_active_categories)

    def _translation(self):
        return self._find_translation()

    translation = property(fget=_translation)

    def _get_absolute_url(self):
        return ('satchmo_brand_view', None, {'brandname': self.slug})

    get_absolute_url = models.permalink(_get_absolute_url)

    def active_products(self):
        return self.products.filter(site=self.site, active=True)

    def has_categories(self):
        return self.active_categories().count() > 0

    def has_content(self):
        return self.has_products() or self.has_categories()

    def has_products(self):
        return self.active_products().count() > 0

    def __unicode__(self):
        return u"%s" % self.slug

    class Meta:
        ordering = ('ordering', 'slug')
        verbose_name = _('Brand')
        verbose_name_plural = _('Brands')
Exemplo n.º 8
0
class VisitEvent(RealEstateAppBaseModel):

    property_fk = models.ForeignKey('propertys.Property')

    visitor_fk = models.ForeignKey('visitcalendar.Visitor')

    date_visit = models.DateTimeField(
        _('Date of visit'),
        unique=True,
        default=datetime.now(),
        help_text=_('Entry with a init of date publicashion'))

    slug = models.SlugField(
        _('slug'),
        unique=True,
        help_text=_('Automatically built from the caption. A slug is a short '
                    'label generally used in URLs.'),
    )

    objects = RealEstateManager()

    class Meta:
        app_label = 'visitcalendar'
        db_table = 'real_estate_app_apps_visitcalendar_visitevent'
        get_latest_by = 'date_visit'
        ordering = ('date_visit', )
        verbose_name = _('Visit')
        verbose_name_plural = _('Visits')

    def __unicode__(self):
        try:
            return u'%s' % self.date_visit.strftime(
                settings.DATETIME_INPUT_FORMATS[0])
        except IndexError:
            return u'%s' % self.date_visit.strftime('%Y-%m-%d %H:%M:%S')
        else:
            raise

    def _visitor(self):
        return self.visitor_first_name + ' ' + self.visitor_last_name

    visitor = property(_visitor)

    def _get_absolute_url(self):
        return ('visitcalendar-detail', None, {
            'slug': str(self.slug),
        })

    get_absolute_url = permalink(_get_absolute_url)
class Message(models.Model):
    """
    A private message from user to user
    """
    subject = models.CharField(_("Subject"), max_length=120)
    body = models.TextField(_("Body"))
    sender = models.ForeignKey(AUTH_USER_MODEL, related_name='sent_messages', verbose_name=_("Sender"))
    recipient = models.ForeignKey(AUTH_USER_MODEL, related_name='received_messages', null=True, blank=True, verbose_name=_("Recipient"))
    parent_msg = models.ForeignKey('self', related_name='next_messages', null=True, blank=True, verbose_name=_("Parent message"))
    sent_at = models.DateTimeField(_("sent at"), null=True, blank=True)
    read_at = models.DateTimeField(_("read at"), null=True, blank=True)
    replied_at = models.DateTimeField(_("replied at"), null=True, blank=True)
    sender_deleted_at = models.IntegerField(_("Sender deleted at"), null=True, blank=True)
    recipient_deleted_at = models.DateTimeField(_("Recipient deleted at"), null=True, blank=True)
    # trash_status = models.IntegerField(_("trash_status"),null=True)
    provider_sent_status = models.IntegerField(_("provider_sent_status"),null=True)
    buyer_display_status = models.IntegerField(_("buyer_display_status"),null=True)
    provider_display_status = models.IntegerField(_("provider_display_status"),null=True)
    
    objects = MessageManager()
    
    def new(self):
        """returns whether the recipient has read the message or not"""
        if self.read_at is not None:
            return False
        return True
        
    def replied(self):
        """returns whether the recipient has written a reply to this message"""
        if self.replied_at is not None:
            return True
        return False
    
    def __unicode__(self):
        return self.subject
    
    def get_absolute_url(self):
        return ('messages_detail', [self.id])
    get_absolute_url = models.permalink(get_absolute_url)
    
    def save(self, **kwargs):
        if not self.id:
            self.sent_at = timezone.now()
        super(Message, self).save(**kwargs) 
    
    class Meta:
        ordering = ['-sent_at']
        verbose_name = _("Message")
        verbose_name_plural = _("Messages")
Exemplo n.º 10
0
class Feedback(models.Model):
    type = models.ForeignKey(Type, verbose_name=_("Type"))
    title = models.CharField(_("Title"), max_length=500)
    description = models.TextField(
        _("Description"),
        blank=True,
        help_text=_('This wiill be viewable by other people - '
                    'do not include any private details such as '
                    'passwords or phone numbers here.'))
    anonymous = models.BooleanField(_("Anonymous"),
                                    blank=True,
                                    help_text=_('Do not show who sent this'))
    private = models.BooleanField(
        _("Private"),
        blank=True,
        help_text=_('Hide from public pages. Only site administrators '
                    'will be able to view and respond to this.'))
    user = models.ForeignKey(User,
                             blank=True,
                             null=True,
                             verbose_name=_("User"))
    created = models.DateTimeField(auto_now_add=True,
                                   blank=True,
                                   null=True,
                                   verbose_name=_("Created at"))
    status = models.ForeignKey(Status, verbose_name=_("Status"))
    duplicate = models.ForeignKey('self',
                                  null=True,
                                  blank=True,
                                  verbose_name=_("Duplicate"))

    def save(self, *args, **kwargs):
        try:
            self.status
        except:
            try:
                default = Status.objects.get(default=True)
            except:
                default = Status.objects.filter()[0]
            self.status = default
        super(Feedback, self).save()

    def get_absolute_url(self):
        return ('djangovoice_item', (self.id, ))

    get_absolute_url = models.permalink(get_absolute_url)

    def __unicode__(self):
        return self.title
Exemplo n.º 11
0
class Category(models.Model):
    title = models.CharField(max_length=250, help_text='Keep within 250 Chars')
    slug = models.SlugField(unique=True)
    description = models.TextField()

    class Meta:
        verbose_name_plural = "Categories"

    def __unicode__(self):
        return self.title

    def get_absolute_url(self):
        return ('DJPlus_category_detail', ('slug'), {'slug': self.slug})

    get_absolute_url = models.permalink(get_absolute_url)
Exemplo n.º 12
0
class Category(models.Model):
    title = models.CharField(max_length=200)
    slug = models.SlugField()

    class Meta:
        ordering = ('title',)
        verbose_name = ('category')
        verbose_name_plural = ('categories')

    def __unicode__(self):
        return self.title

    def get_absolute_url(self):
        return 'leon_category', None, {'slug': self.slug}
    get_absolute_url = models.permalink(get_absolute_url)
Exemplo n.º 13
0
class HashTag(models.Model):
    name = models.TextField(max_length=50, blank=False, null=False)

    def __str__(self):
        return "#%s" % self.name

    class Meta:
        db_table = 'hashtag'
        verbose_name = 'Hashtag'
        verbose_name_plural = 'Hashtags'

    def get_absolute_url(self):
        return ('hashtag', None, {'hashtag': str(self.name)})

    get_absolute_url = models.permalink(get_absolute_url)
Exemplo n.º 14
0
class UserProfile(models.Model):
    firstName = models.CharField(max_length=100, verbose_name="First Name")
    lastName = models.CharField(max_length=100, verbose_name="Last Name")
    location = models.CharField(max_length=100,
                                verbose_name="Current Location")
    email = models.EmailField()
    phoneNum = models.IntegerField(max_length=100, verbose_name="Phone Number")
    user = models.OneToOneField(User, parent_link=True)

    def get_absolute_url(self):
        return ('profiles_profile_detail', (), {
            'username': self.user.username
        })

    get_absolute_url = models.permalink(get_absolute_url)
Exemplo n.º 15
0
class Knot(models.Model):
    author = models.ManyToManyField(User, related_name="author_knots", help_text="Authors of post.")

    title = models.CharField(_('title'), max_length=44, help_text="Post title.")
    slug = models.SlugField(_('slug'), blank=True, unique=True, help_text="Post slug (auto generated).")
    short_url = models.CharField(_('short'), max_length=100, blank=True, help_text="Short link for sharing.")
    tagline = models.CharField(_('tagline'), max_length=160, blank=True, help_text="Post tagline, a short, catchy sentence.")
    blurb = models.CharField(_('blurb'), max_length=250, blank=True, help_text="Post blurb, a quick overview.")
    date = models.DateTimeField(_('date published'), help_text="Date published.")
    strand_a = models.ForeignKey(Strand, related_name='strand_a')
    strand_b = models.ForeignKey(Strand, related_name='strand_b')
    body = models.TextField(_('body'), blank=True, help_text="Post body.")
    style = models.TextField(_('style'), blank=True, help_text="Post style (JSON string).")
    notes = models.TextField(_('notes'), blank=True, help_text="Post notes.")
    published = models.BooleanField(_('published'), blank=True, help_text="Is post published?")
    allow_comments = models.BooleanField(_('allow comments'), help_text="Can people comment?")
    allow_rss = models.BooleanField(_('allow rss'), help_text="Can the knot be included in RSS feeds?")
    location = models.ManyToManyField(Location, null=True, blank=True, related_name="location", help_text="Associated locations.")
    license = models.ForeignKey(License, null=True, blank=True, related_name="license", help_text="License applied to post.")
    
    def save(self):
        if not self.slug:
            slug = defaultfilters.slugify( self.title )
            try:
                existing = Knot.objects.get(slug=slug)
            except Knot.DoesNotExist:
                pass
            else:
                slug = '%s-%s' % (slug, (existing.count() + 1))
            self.slug=slug
        while not self.short_url:
            count = Knot.objects.count()
            if count < 1:
                count = 1
            short_url = ''.join(random_alphanumeric(int(math.log(count,62))+1))
            if short_url not in RESERVED_WORDS:
                try:
                    existing = Knot.objects.get(short_url=short_url)
                except Knot.DoesNotExist:
                    self.short_url = short_url
        super( Knot, self ).save()

    def __unicode__(self):
        return u'%s' % self.title

    def get_absolute_url(self):
        return ('display_knot', [str(self.slug)])
    get_absolute_url = models.permalink(get_absolute_url)
Exemplo n.º 16
0
class Code_base(models.Model):
    program_name = models.CharField(max_length=50, core=True)
    version = models.CharField(max_length=40, core=True)
    compile_options = models.CharField(max_length=100)

    def __str__(self):
        return "%s v.%s" % (self.program_name, self.version)

    def get_absolute_url(self):
        return ('relay.warnings.views.code_detail', [str(self.id)])

    get_absolute_url = permalink(get_absolute_url)

    class Admin:
        # Admin options go here
        pass
Exemplo n.º 17
0
class Category(models.Model):
    title = models.CharField(max_length=200)
    slug = models.SlugField()

    class Meta:
        verbose_name = '分类'
        verbose_name_plural = '分类'
        ordering = ('title', )

    def __str__(self):
        return self.title

    def get_absolut_url(self):
        return ('dpress_category', None, {'category': self.slug})

    get_absolut_url = models.permalink(get_absolut_url)
Exemplo n.º 18
0
class UserProfile(models.Model):
    user = models.ForeignKey(User, unique=True)
    telefono = PhoneNumberField()

    def __unicode__(self):
        if self.user.first_name and self.user.last_name:
            return self.user.first_name + " " + self.user.last_name
        else:
            return self.user.username

    def get_absolute_url(self):
        return ('profiles_profile_detail', (), {
            'username': self.user.username
        })

    get_absolute_url = models.permalink(get_absolute_url)
Exemplo n.º 19
0
    def __init__(self, model, **kwargs):
        self.model = model
        for key, value in kwargs.items():
            if not hasattr(self, key):
                raise TypeError('%s() received an invalid keyword %r' % (
                    self.__class__.__name__, key))
            setattr(self, key, value)

        if not hasattr(self.model, 'get_absolute_url'):
            # Add a simple primary key based URL to the model if it does not
            # have one yet
            self.model.get_absolute_url = models.permalink(
                lambda self: (
                    '%s_%s_detail' % app_model_label(self),
                    (self.pk,),
                    {}))
Exemplo n.º 20
0
class UserProfile(models.Model):
    """Additional information about a User."""

    user = AutoOneToOneField('auth.User',
                             verbose_name=_('User'),
                             related_name='profile')
    whitelisted = models.BooleanField(_('Whitelisted'), default=False)
    banned = models.BooleanField(_('Banned'), default=False)
    homepage = models.CharField(_('Homepage'), max_length=100, blank=True)
    allow_ads = models.BooleanField(
        _('See paid advertising'),
        help_text=_('If unchecked, you will still see community ads.'),
        default=True,
    )
    allow_email = models.BooleanField(
        _('Allow email'),
        help_text=_('Show your email on VCS contributions.'),
        default=True,
    )

    def __str__(self):
        return (ugettext("%(username)s's profile") % {
            'username': self.user.username
        })

    def get_absolute_url(self):
        return ('profiles_profile_detail', (), {
            'username': self.user.username
        })

    get_absolute_url = models.permalink(get_absolute_url)

    def get_contribution_details(self):
        """
        Get the line to put into commits to attribute the author.

        Returns a tuple (name, email)
        """
        if self.user.first_name and self.user.last_name:
            name = '{} {}'.format(self.user.first_name, self.user.last_name)
        else:
            name = self.user.username
        if self.allow_email:
            email = self.user.email
        else:
            email = STANDARD_EMAIL
        return (name, email)
Exemplo n.º 21
0
class Conversation(models.Model):
    id = models.IntegerField(primary_key=True, editable=False)
    title = models.CharField(max_length=500, blank=True)
    conversation_text = models.TextField()

    pub_date = models.DateTimeField(default=datetime.datetime.now)
    user = models.ForeignKey(User)

    class Meta:
        ordering = ['-pub_date']

    def save(self):
        try:
            self.conversationline_set.all().delete()
        except:
            pass
        api = get_user_api(self.user.username)
        if api:
            if not self.id:
                post = api.write_conversation(
                    title=self.title, conversation=self.conversation_text)
                self.id = post['id']
        super(Conversation, self).save()

        lines = self.conversation_text.split('\n')
        for line in lines:
            c = ConversationLine(conversation=self, line=line)
            c.save()

    def __unicode__(self):
        if self.title:
            return "%s (Conversation)" % self.title
        else:
            return "Conversation"

    def get_absolute_url(self):
        return ('djumblr_conversation_detail', (), {
            'year': self.pub_date.strftime("%Y"),
            'month': self.pub_date.strftime("%b").lower(),
            'day': self.pub_date.strftime("%d"),
            'id': self.id
        })

    get_absolute_url = models.permalink(get_absolute_url)

    def shared_display(self):
        return display_tumbl(self, "djumblr/display/conversation.html")
Exemplo n.º 22
0
class Category(models.Model):
    title           = models.CharField(_('title'), max_length=200)
    slug            = models.SlugField(_('slug'))

    class Meta:
        verbose_name        = _('category')
        verbose_name_plural = _('categorys')
        ordering            = ('title',)

    def __unicode__(self):
        return self.title

    def get_absolute_url(self):
        return ('dpress_category', None, {
            'category': self.slug
    })
    get_absolute_url = models.permalink(get_absolute_url)
Exemplo n.º 23
0
class Run(models.Model):
    time_of_run = models.DateTimeField(editable=True, auto_now_add=True)
    code = models.ForeignKey(Code_base, limit_choices_to={})
    changes_to_analysis = models.TextField(core=True)
    analysis_settings = models.TextField(core=True)

    def __str__(self):
        return str(self.code) + " " + str(self.time_of_run)

    def get_absolute_url(self):
        return ('relay.warnings.views.run_detail', [str(self.id)])

    get_absolute_url = permalink(get_absolute_url)

    class Admin:
        list_display = ('id', 'code', 'time_of_run')
        list_filter = ('code', 'time_of_run')
Exemplo n.º 24
0
class Message(models.Model):
    """
    A private message from user to user
    """
    subject = models.CharField(_("Subject"), max_length=120)
    body = models.TextField(_("Body"))
    sender = models.ForeignKey(User, related_name='sent_messages', verbose_name=_("Sender"))
    recipient = models.ForeignKey(User, related_name='received_messages', null=True, blank=True, verbose_name=_("Recipient"))
    parent_msg = models.ForeignKey('self', related_name='next_messages', null=True, blank=True, verbose_name=_("Parent message"))
    sent_at = models.DateTimeField(_("sent at"), null=True, blank=True)
    read_at = models.DateTimeField(_("read at"), null=True, blank=True)
    replied_at = models.DateTimeField(_("replied at"), null=True, blank=True)
    sender_deleted_at = models.DateTimeField(_("Sender deleted at"), null=True, blank=True)
    recipient_deleted_at = models.DateTimeField(_("Recipient deleted at"), null=True, blank=True)
    
    objects = MessageManager()
    
    def new(self):
        """returns whether the recipient has read the message or not"""
        if self.read_at is not None:
            return False
        return True
        
    def replied(self):
        """returns whether the recipient has written a reply to this message"""
        if self.replied_at is not None:
            return True
        return False
    
    def __unicode__(self):
        return self.subject
    
    def get_absolute_url(self):
        return ('messages_detail', [self.id])
    get_absolute_url = models.permalink(get_absolute_url)
    
    def save(self, force_insert=False, force_update=False):
        if not self.id:
            self.sent_at = datetime.datetime.now()
        super(Message, self).save(force_insert, force_update) 
    
    class Meta:
        db_table = "messages_message"
        ordering = ['-sent_at']
        verbose_name = _("Message")
        verbose_name_plural = _("Messages")
Exemplo n.º 25
0
class Post(models.Model, PictureMixin):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    pub_date = models.DateTimeField(default=timezone_now())
    text = models.TextField()
    notifications = GenericRelation(
        Notification,
        content_type_field='action_object_content_type_id',
        object_id_field='action_object_object_id')
    pictures = GenericRelation(UploadedFile,
                               content_type_field='content_type_id',
                               object_id_field='object_pk')
    comments_set = GenericRelation(
        PictureComment,
        content_type_field='content_type',
        object_id_field='object_pk',
    )
    tags = models.ManyToManyField(HashTag)

    def __str__(self):
        return "%s posted %s on %s" % (self.user, self.text, self.pub_date)

    class Meta:
        db_table = 'user_post'
        verbose_name = 'post'
        verbose_name_plural = 'posts'

    def save(self, *args, **kwargs):
        # first must save the object before we can use the many_to_many field
        super(Post, self).save(*args, **kwargs)
        link_hashtags_to_model(self.text, self, self.user)
        notify_on_mention(self.text, self, self.user)
        # generate thumbnail picture version
        if self.pictures is not None:
            for p in self.pictures.all():
                p.create_thumbnail()

    def delete(self, *args, **kwargs):

        super(Post, self).delete(*args, **kwargs)

    delete.alters_data = True

    def get_absolute_url(self):
        return ('post_detail', None, {'post': str(self.pk)})

    get_absolute_url = models.permalink(get_absolute_url)
Exemplo n.º 26
0
class UserProfile(models.Model):
    """Additional information about a User.
    """
    user = models.ForeignKey(User,
                             verbose_name=_('User'),
                             unique=True,
                             related_name='profile')
    whitelisted = models.BooleanField(_('Whitelisted'))
    homepage = models.CharField(_('Homepage'), max_length=100, blank=True)
    allow_email = models.BooleanField(_('Allow email'),
                                      help_text=_('Show your email on VCS '
                                                  'contributions.'),
                                      default=True)

    def __unicode__(self):
        return (ugettext("%(username)s's profile") % {
            'username': self.user.username
        })

    def get_form(self):
        from .forms import UserProfileForm
        return UserProfileForm(instance=self)

    def get_absolute_url(self):
        return ('profiles_profile_detail', (), {
            'username': self.user.username
        })

    get_absolute_url = models.permalink(get_absolute_url)

    def get_contribution_details(self):
        """
        Gets the line to put into commits to attribute the author.

        Returns a tuple (name, email)
        """
        if self.user.first_name and self.user.last_name:
            name = '%s %s' % (self.user.first_name, self.user.last_name)
        else:
            name = self.user.username
        if self.allow_email:
            email = self.user.email
        else:
            email = STANDARD_EMAIL
        return (name, email)
Exemplo n.º 27
0
class Notice(models.Model):

    user = models.ForeignKey(User,
                             verbose_name=_('user'),
                             blank=True,
                             null=True)
    email = models.EmailField(max_length=96, blank=True, null=True)
    message = models.TextField(_('message'))
    notice_type = models.ForeignKey(NoticeType, verbose_name=_('notice type'))
    added = models.DateTimeField(_('added'), default=datetime.datetime.now)
    unseen = models.BooleanField(_('unseen'), default=True)
    archived = models.BooleanField(_('archived'), default=False)
    on_site = models.BooleanField(_('on site'))

    objects = NoticeManager()

    def __unicode__(self):
        return self.message

    def archive(self):
        self.archived = True
        self.save()

    def is_unseen(self):
        """
        returns value of self.unseen but also changes it to false.

        Use this in a template to mark an unseen notice differently the first
        time it is shown.
        """
        unseen = self.unseen
        if unseen:
            self.unseen = False
            self.save()
        return unseen

    class Meta:
        ordering = ["-added"]
        verbose_name = _("notice")
        verbose_name_plural = _("notices")

    def get_absolute_url(self):
        return ("notification_notice", [str(self.pk)])

    get_absolute_url = models.permalink(get_absolute_url)
Exemplo n.º 28
0
class Link(models.Model):
    # Metadata.
    enable_comments = models.BooleanField(default=True)
    post_elsewhere = models.BooleanField('Post to Delicious',
                                         default=True,
                                         help_text='If checked, this link will be posted both to your blog and your del.icio.us account.')
    posted_by = models.ForeignKey(User)
    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.')
    title = models.CharField(max_length=250)

    # The actual link bits.
    description = models.TextField(blank=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. Optional.')
    tags = TagField()
    url = models.URLField(unique=True)

    class Meta:
        ordering = ['-pub_date']

    def __unicode__(self):
        return self.title

    def save(self, force_insert=False, force_update=False):
        if not self.id and self.post_elsewhere:
            import pydelicious
            from django.utils.encoding import smart_str
            pydelicious.add(settings.DELICIOUS_USER, settings.DELICIOUS_PASSWORD,
                            smart_str(self.url), smart_str(self.title),
                            smart_str(self.tags))
        #if self.description:
        #    self.description_html = markdown(self.description)
        super(Link, self).save()

    def get_absolute_url(self):

        return ('zeus_link_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)
Exemplo n.º 29
0
class BrandCategory(models.Model, TranslatedObjectMixin):
    """A category within a brand"""
    slug = models.SlugField(_("Slug"), help_text=_("Used for URLs"))
    brand = models.ForeignKey(Brand, related_name="categories")
    products = models.ManyToManyField(Product,
                                      blank=True,
                                      verbose_name=_("Products"),
                                      through='BrandCategoryProduct')
    ordering = models.IntegerField(_("Ordering"))
    active = models.BooleanField(default=True)

    objects = BrandCategoryManager()

    def _translation(self):
        return self._find_translation()

    translation = property(fget=_translation)

    def _get_absolute_url(self):
        return ('satchmo_brand_category_view', None, {
            'brandname': self.brand.slug,
            'catname': self.slug
        })

    get_absolute_url = models.permalink(_get_absolute_url)

    def active_products(self):
        return self.products.filter(site=self.brand.site).filter(active=True)

    def has_categories(self):
        return False

    def has_content(self):
        return self.active_products()

    def has_products(self):
        return self.active_products().count > 0

    def __unicode__(self):
        return u"%s: %s" % (self.brand.slug, self.slug)

    class Meta:
        ordering = ('ordering', 'slug')
        verbose_name = _('Brand Category')
        verbose_name_plural = _('Categories')
Exemplo n.º 30
0
class Week(models.Model):
    #date must be unique
    #and when users involved, user+date combo
    #is what must be unique
    date = models.DateField()
    name = models.CharField(max_length=100, editable=False)
    days = models.ManyToManyField(Day, editable=False)
    slug = models.SlugField(unique=True, editable=False)

    class Meta:
        pass

    def __unicode__(self):
        return self.name

    def save(self, force_insert=False, force_update=False):
        """
        if date != monday:
            date = the previous monday

        name = self.date to self.date+6

        """
        #If self.date is not a Monday, then make it a Monday
        date = self.date
        weekday = date.weekday()
        if weekday != 0:
            a_monday = date - datetime.timedelta(days=weekday)
            self.date = a_monday

        start_of_week = self.date
        end_of_week = self.date + datetime.timedelta(days=6)
        self.name = "%s to %s" % (
            start_of_week.strftime('%a %b %d, %Y'),
            end_of_week.strftime('%a %b %d, %Y'),
        )

        self.slug = slugify(self.date.strftime('%a %b %d, %Y'))

        super(Week, self).save(force_insert, force_update)

    def get_absolute_url(self):
        return ('mealweek_week_detail', (), {'slug': self.slug})

    get_absolute_url = models.permalink(get_absolute_url)
Exemplo n.º 31
0
class Photo(models.Model):
    id = models.IntegerField(primary_key=True, editable=False)
    source = models.URLField(blank=True)
    photo = models.ImageField(upload_to="/photos", blank=True)
    caption = models.TextField(blank=True)
    click_through_url = models.URLField(blank=True)

    pub_date = models.DateTimeField(default=datetime.datetime.now)
    user = models.ForeignKey(User)

    class Meta:
        ordering = ['-pub_date']

    def save(self):
        api = get_user_api(self.user.username)
        if api:
            if not self.id:
                if self.source:
                    post = api.write_photo(
                        source=self.source,
                        caption=self.caption,
                        click_through_url=self.click_through_url)
                elif self.photo:
                    post = api.write_photo(
                        data=open(self.photo),
                        caption=self.caption,
                        click_through_url=self.click_through_url)
                self.id = post['id']
        super(Photo, self).save()

    def __unicode__(self):
        return "Photo"

    def get_absolute_url(self):
        return ('djumblr_photo_detail', (), {
            'year': self.pub_date.strftime("%Y"),
            'month': self.pub_date.strftime("%b").lower(),
            'day': self.pub_date.strftime("%d"),
            'object_id': self.id
        })

    get_absolute_url = models.permalink(get_absolute_url)

    def shared_display(self):
        return display_tumbl(self, "djumblr/display/photo.html")
Exemplo n.º 32
0
class Profile(models.Model):
    GENDER_CHOICES = (('M', _('Male')), ('F', _('Female')),)
    USER_CHOICES = (
    ('User', _('User')), ('Agent', _('Agent')), ('Contact', _('Contact')))

    user = models.OneToOneField(User, on_delete=models.CASCADE)
    about = models.TextField(_('about'), max_length=500, blank=True, default='')
    gender = models.CharField(_('gender'), max_length=5, choices=GENDER_CHOICES, null=True, default='M')

    url = models.URLField(_('website'), blank=True)
    location = models.CharField(_('location'), max_length=150, blank=True, default='')
    phone = models.CharField(max_length=20, null=True, blank=True, default='')
    city = models.CharField(max_length=100, default='', null=True, blank=True)
    country = models.CharField(max_length=100, default='', null=True, blank=True)

    image = models.ImageField(_('photo'), upload_to='upload/user_images', default="upload/blog_photos/amor-590x336.jpg",
                              max_length=1024)
    image_thumbnail = ImageSpecField(source="image", processors=[SmartResize(100, 100)], format="PNG",
                                     options={'quality': 60})
    image_big_thumbnail = ImageSpecField(source="image", processors=[SmartResize(200, 200)], format="PNG",
                                         options={'quality': 60})
    image_pin = ImageSpecField(source="image", processors=[SmartResize(32, 32)], format="PNG", options={'quality': 60})
    image_comment_thumb = ImageSpecField(source="image", processors=[SmartResize(45, 45)], format="PNG",
                                         options={'quality': 60})

    profile_type = models.CharField(_('Type'), max_length=15, choices=USER_CHOICES, default='User')

    pub_date = models.DateTimeField(auto_now_add=True)
    update_date = models.DateTimeField(auto_now=True)

    is_influencer = models.BooleanField(_('influencer'), default=False,
                                        help_text='This user is a content provider and can be followed by other users')

    class Meta:
        verbose_name_plural = _('User profiles')

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

    def get_absolute_url(self):
        return ('profile_detail', (), {'username': self.user.username})

    get_absolute_url = models.permalink(get_absolute_url)
Exemplo n.º 33
0
class Language(models.Model):
    name = models.CharField(max_length=50, unique=True)
    slug = models.SlugField(editable=False)

    def save(self, **kwargs):
        if not self.id:
            self.slug = slugify(self.name)
        super(Language, self).save(kwargs)

    def get_absolute_url(self):
        return ('mloss.software.views.list.software_by_language', (), {
            'slug': self.slug
        })

    get_absolute_url = models.permalink(get_absolute_url)

    def __unicode__(self):
        return unicode(self.name)
Exemplo n.º 34
0
class TutorialCategory(models.Model):
    name = models.CharField(max_length=200)

    def __unicode__(self):
        return self.name

    def get_absolute_url(self):
        return ('resources_tutorial_category', (), {
            'id': self.id,
        })

    get_absolute_url = models.permalink(get_absolute_url)

    class Meta:
        verbose_name_plural = "Tutorial Categories"
        ordering = [
            'name',
        ]
Exemplo n.º 35
0
	def get_absolute_url(self):
		return('coltrane_link_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)
Exemplo n.º 36
0
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from thumbs import ImageWithThumbsField

import lifestream.models

# short_name is a user's first name and last initial
User.short_name = property(lambda self: "%s %s." % (self.first_name, self.last_name[0:1]))
User.get_absolute_url = models.permalink(lambda self: ('account_view', (), { 'username': self.username, }))

DEFAULT_PROFILE_IMAGE_PATH = 'profile_images/default_breakout_profile_image.png'

class UserProfile(models.Model):
    GENDER_CHOICES = (
        ('M', 'Male'),
        ('F', 'Female'),
    )
    
    created_on = models.DateTimeField(auto_now_add=True)
    updated_on = models.DateTimeField(auto_now=True)
    user = models.ForeignKey(User)
    profile_image = ImageWithThumbsField(max_length=400, upload_to='profile_images', sizes=((48, 48), (64, 64), (200, 200)), default=ImageWithThumbsField(DEFAULT_PROFILE_IMAGE_PATH))
    age = models.PositiveSmallIntegerField(blank=True, null=True)
    gender = models.CharField(max_length=1, choices=GENDER_CHOICES, blank=True, null=True)
    occupation = models.CharField(max_length=100, blank=True, null=True)
    twitter_access_token = models.CharField(max_length=500, blank=True, null=True)
    twitter_user = models.ForeignKey(lifestream.models.TwitterUser, related_name='twitter_user', blank=True, null=True)
    
    class Meta:
Exemplo n.º 37
0
    template = get_template(template_src)
    context = Context(context_dict)
    html  = template.render(context)
    result = StringIO.StringIO()

    pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("utf-8")), result)
    if not pdf.err:
        response = HttpResponse(result.getvalue(), mimetype='application/pdf')
        response['Content-Disposition'] = 'attachment; filename=report.pdf'
        return response
    return HttpResponse('We had some errors<pre>%s</pre>' % escape(html))

def help(request):
    if request.method == "POST":
        if request.POST['clickedButton'] == "export_pdf":
            return render_to_response("base.html", context_instance=RequestContext(request))
    return render_to_response("help.html", context_instance=RequestContext(request))

def thanks(request):
    return render_to_response('thanks.html', context_instance=RequestContext(request))

def topdf(request):
    return render_to_pdf('app/list_org.html',{
        'pagesize': 'A4'})

#method routes to the view ``profiles.views.profile_detail``, passing the username
@models.permalink
def get_absolute_url(self):
        return ('profiles_profile_detail', (), { 'username': self.user.username })
get_absolute_url = models.permalink(get_absolute_url)
Exemplo n.º 38
0
    def get_absolute_url(self):
        """
        Needed for the profiles application, returns a url ref
        """
        return 'profiles_profile_detail', (), { 'username': self.user.username }
	get_absolute_url = models.permalink(get_absolute_url)
Exemplo n.º 39
0
from django.contrib.sites.models import Site
from django.contrib.comments.models import Comment
from django.contrib.comments.signals import comment_will_be_posted
from django.contrib.comments.moderation import CommentModerator, moderator

# Fetch a Site  object so it would know where you were running the development
# server. Whenever you're  running with this database and settings file, you
# can get that Site object.

# current_site = Site.objects.get_current()
# akismet_api = Akismet(key=settings.AKISMET_API_KEY,
                       # blog_url="http://%s/" %Site.objects.get_current().domain)



Tag.get_absolute_url = models.permalink(
              lambda self: ('coltrane_all_items_by_tag', (), {'tag': self.name.lower()}))


 
        
        
# ------------------------------------------------------------------------------
# Content, Links etc
# ------------------------------------------------------------------------------

class Location(models.Model):
    
    
    title = models.CharField(max_length=250, help_text='Maximum 250 characters.')
    slug = models.SlugField(unique=True, help_text=""" Suggested value automatically 
                            generated from title. Must be unique.""")
Exemplo n.º 40
0
        def _model(data, fields=()):
            """
            Models. Will respect the `fields` and/or
            `exclude` on the handler (see `typemapper`.)
            """
            ret = { }
            handler = self.in_typemapper(type(data), self.anonymous)
            get_absolute_uri = False

            if handler or fields:
                v = lambda f: getattr(data, f.attname)

                if not fields:
                    """
                    Fields was not specified, try to find teh correct
                    version in the typemapper we were sent.
                    """
                    mapped = self.in_typemapper(type(data), self.anonymous)
                    get_fields = set(mapped.fields)
                    exclude_fields = set(mapped.exclude).difference(get_fields)

                    if 'absolute_uri' in get_fields:
                        get_absolute_uri = True

                    if not get_fields:
                        get_fields = set([ f.attname.replace("_id", "", 1)
                            for f in data._meta.fields ])

                    # sets can be negated.
                    for exclude in exclude_fields:
                        if isinstance(exclude, basestring):
                            get_fields.discard(exclude)

                        elif isinstance(exclude, re._pattern_type):
                            for field in get_fields.copy():
                                if exclude.match(field):
                                    get_fields.discard(field)

                else:
                    get_fields = set(fields)

                met_fields = self.method_fields(handler, get_fields)

                for f in data._meta.local_fields:
                    if f.serialize and not any([ p in met_fields for p in [ f.attname, f.name ]]):
                        if not f.rel:
                            if f.attname in get_fields:
                                ret[f.attname] = _any(v(f))
                                get_fields.remove(f.attname)
                        else:
                            if f.attname[:-3] in get_fields:
                                ret[f.name] = _fk(data, f)
                                get_fields.remove(f.name)

                for mf in data._meta.many_to_many:
                    if mf.serialize and mf.attname not in met_fields:
                        if mf.attname in get_fields:
                            ret[mf.name] = _m2m(data, mf)
                            get_fields.remove(mf.name)

                # try to get the remainder of fields
                for maybe_field in get_fields:

                    if isinstance(maybe_field, (list, tuple)):
                        model, fields = maybe_field
                        inst = getattr(data, model, None)

                        if inst:
                            if hasattr(inst, 'all'):
                                ret[model] = _related(inst, fields)
                            elif callable(inst):
                                if len(inspect.getargspec(inst)[0]) == 1:
                                    ret[model] = _any(inst(), fields)
                            else:
                                ret[model] = _model(inst, fields)

                    elif maybe_field in met_fields:
                        # Overriding normal field which has a "resource method"
                        # so you can alter the contents of certain fields without
                        # using different names.
                        ret[maybe_field] = _any(met_fields[maybe_field](data))

                    else:
                        maybe = getattr(data, maybe_field, None)
                        if maybe:
                            if callable(maybe):
                                if len(inspect.getargspec(maybe)[0]) == 1:
                                    ret[maybe_field] = _any(maybe())
                            else:
                                ret[maybe_field] = _any(maybe)
                        else:
                            handler_f = getattr(handler or self.handler, maybe_field, None)

                            if handler_f:
                                ret[maybe_field] = _any(handler_f(data))

            else:
                for f in data._meta.fields:
                    ret[f.attname] = _any(getattr(data, f.attname))

                fields = dir(data.__class__) + ret.keys()
                add_ons = [k for k in dir(data) if k not in fields]

                for k in add_ons:
                    ret[k] = _any(getattr(data, k))

            # resouce uri
            if self.in_typemapper(type(data), self.anonymous):
                handler = self.in_typemapper(type(data), self.anonymous)
                if hasattr(handler, 'resource_uri'):
                    url_id, fields = handler.resource_uri()
                    ret['resource_uri'] = permalink( lambda: (url_id,
                        (getattr(data, f) for f in fields) ) )()

            if hasattr(data, 'get_api_url') and 'resource_uri' not in ret:
                try: ret['resource_uri'] = data.get_api_url()
                except: pass

            # absolute uri
            if hasattr(data, 'get_absolute_url') and get_absolute_uri:
                try: ret['absolute_uri'] = data.get_absolute_url()
                except: pass

            return ret
Exemplo n.º 41
0
    def __new__(cls, name, bases, attrs):
        cls = super(BMFModelBase, cls).__new__(cls, name, bases, attrs)

        parents = [b for b in bases if isinstance(b, BMFModelBase)]
        if not parents:
            # If this is the ModelBase-Class itself - do nothing
            return cls
        if cls._meta.abstract:
            # Don't do anything on abstract models
            return cls

        # make bmf-attributes
        cls._bmfmeta = BMFOptions(cls, cls._meta, getattr(cls, 'BMFMeta', None))

        if type(cls._meta.permissions) is not tuple:
            cls._meta.permissions = tuple(cls._meta.permissions)

        # generate permissions
        if not cls._bmfmeta.only_related:
            cls._meta.permissions += (
                ('view_' + cls._meta.model_name, u'Can view %s' % cls.__name__),
            )
        if cls._bmfmeta.can_clone:
            cls._meta.permissions += (
                ('clone_' + cls._meta.model_name, u'Can clone %s' % cls.__name__),
            )
        if cls._bmfmeta.has_comments:
            cls._meta.permissions += (
                ('comment_' + cls._meta.model_name, u'Can comment on %s' % cls.__name__),
            )
        if cls._bmfmeta.has_files:
            cls._meta.permissions += (
                ('addfile_' + cls._meta.model_name, u'Can add files to %s' % cls.__name__),
            )

        # add field: workflow field
        if cls._bmfmeta.has_workflow:
            try:
                field = cls._meta.get_field(cls._bmfmeta.workflow_field_name)
                if not isinstance(field, WorkflowField):
                    raise ImproperlyConfigured(
                        '%s is not a WorkflowField in %s' % (
                            cls._bmfmeta.workflow_field_name,
                            cls.__name__
                        )
                    )

            except (models.FieldDoesNotExist, AppRegistryNotReady):
                field = WorkflowField(workflow=cls._bmfmeta.workflow_cls)
                field.contribute_to_class(cls, cls._bmfmeta.workflow_field_name)

        # add field: modified
        try:
            cls._meta.get_field('modified')
        except (models.FieldDoesNotExist, AppRegistryNotReady):
            field = models.DateTimeField(
                _("Modified"),
                auto_now=True,
                editable=False,
                null=True,
                blank=False,
            )
            field.contribute_to_class(cls, 'modified')

        # add field: created
        try:
            cls._meta.get_field('created')
        except (models.FieldDoesNotExist, AppRegistryNotReady):
            field = models.DateTimeField(
                _("Created"),
                auto_now_add=True,
                editable=False,
                null=True,
                blank=False,
            )
            field.contribute_to_class(cls, 'created')

        # add field: modified by
        try:
            cls._meta.get_field('modified_by')
        except (models.FieldDoesNotExist, AppRegistryNotReady):
            field = models.ForeignKey(
                getattr(settings, 'AUTH_USER_MODEL', 'auth.User'),
                verbose_name=_("Modified by"),
                null=True, blank=True, editable=False,
                related_name="+", on_delete=models.SET_NULL
            )
            field.contribute_to_class(cls, 'modified_by')

        # add field: created by
        try:
            cls._meta.get_field('created_by')
        except (models.FieldDoesNotExist, AppRegistryNotReady):
            field = models.ForeignKey(
                getattr(settings, 'AUTH_USER_MODEL', 'auth.User'),
                verbose_name=_("Created by"),
                null=True, blank=True, editable=False,
                related_name="+", on_delete=models.SET_NULL
            )
            field.contribute_to_class(cls, 'created_by')

        # TODO add model from app config
        try:
            cls._meta.get_field('djangobmf_activity')
        except (models.FieldDoesNotExist, AppRegistryNotReady):
            field = GenericRelation(
                "djangobmf.Activity",
                content_type_field='parent_ct',
                object_id_field='parent_id',
            )
            field.contribute_to_class(cls, 'djangobmf_activity')

        # TODO add model from app config
        try:
            cls._meta.get_field('djangobmf_notification')
        except (models.FieldDoesNotExist, AppRegistryNotReady):
            field = GenericRelation(
                "djangobmf.Notification",
                content_type_field='watch_ct',
                object_id_field='watch_id',
            )
            field.contribute_to_class(cls, 'djangobmf_notification')

        # instancemethod: bmfget_project
        def bmfget_project(self):
            """
            The result of this value is currently used by the document-management system
            to connect the file uploaded to this model with a project instance

            Default: None
            """
            return None

        setattr(cls, 'bmfget_project', bmfget_project)

        # instancemethod: bmfget_customer
        def bmfget_customer(self):
            """
            The result of this value is currently used by the document-management system
            to connect the file uploaded to this model with a customer instance

            Default: None
            """
            return None

        setattr(cls, 'bmfget_customer', bmfget_customer)

        # instancemethod: bmfmodule_detail
        def bmfmodule_detail(self):
            """
            A permalink to the default view of this model in the BMF-System
            """
            return ('%s:detail' % self._bmfmeta.namespace_detail, (), {"pk": self.pk})

        setattr(cls, 'bmfmodule_detail', models.permalink(bmfmodule_detail))

        # instancemethod: get_absolute_url
        def get_absolute_url(self):
            return self.bmfmodule_detail()

        setattr(cls, 'get_absolute_url', get_absolute_url)

        # classmethod: bmfmodule_list
        def bmfmodule_list(cls, manager="all"):
            """
            """
            return ('%s:get' % cls._bmfmeta.namespace_api, (), {"manager": manager})

        setattr(cls, 'bmfmodule_list', classmethod(models.permalink(bmfmodule_list)))

        if cls._bmfmeta.clean:
            if not hasattr(cls, 'bmf_clean') and not cls._meta.abstract:
                raise ImproperlyConfigured('%s has not a bmf_clean method' % (cls.__name__))

        # add history signals for this model
        add_signals(cls)

        if cls._bmfmeta.has_workflow:

            def post_init_workflow(sender, instance, *args, **kwargs):
                workflow = getattr(instance, instance._bmfmeta.workflow_field_name)
                workflow.set_django_object(instance)
                instance._bmfmeta.workflow = workflow

            signals.post_init.connect(post_init_workflow, sender=cls, weak=False)

        if cls._bmfmeta.observed_fields:

            def post_init_observed_fields(sender, instance, *args, **kwargs):
                if instance.pk:
                    for key in instance._bmfmeta.observed_fields:
                        instance._bmfmeta.changelog[key] = getattr(instance, key)

            signals.post_init.connect(post_init_observed_fields, sender=cls, weak=False)

#       # add signals from base-classes
#       if hasattr(cls,'pre_save'):
#           if isinstance(cls.pre_save, types.FunctionType):
#               signals.pre_save.connect(cls.pre_save, sender=cls, weak=False)

#       if hasattr(cls,'post_init'):
#           if isinstance(cls.post_init, types.FunctionType):
#               signals.post_init.connect(cls.post_init, sender=cls, weak=False)

        if hasattr(cls, 'post_save'):
            """
            @staticmethod
            def post_save(sender, instance, created, raw, *args, **kwargs):
              pass
            """
            if isinstance(cls.post_save, types.FunctionType):
                signals.post_save.connect(cls.post_save, sender=cls, weak=False)

        if hasattr(cls, 'post_delete'):
            """
            @staticmethod
            def post_delete(sender, instance, *args, **kwargs):
              pass
            """
            if isinstance(cls.post_delete, types.FunctionType):
                signals.post_delete.connect(cls.post_delete, sender=cls, weak=False)

        return cls
Exemplo n.º 42
0
def get_absolute_url(self):
	return ('profiles_profile_detail', (), {'username': self.user.username })
	get_absolute_url = models.permalink(get_absolute_url)
Exemplo n.º 43
0
	def get_absolute_url(self):
		return ('gallery_detail', (), {'slug': self.slug})
		get_absolute_url = models.permalink(get_absolute_url)
Exemplo n.º 44
0
    name = models.CharField(blank=True,  max_length=80)
	initials = models.CharField(blank=True, max_length=10)
    url = models.URLField(_('url'), blank=True, verify_exists=False)
    last_checked = models.DateTimeField(_('last checked'), blank=True, null=True)
    polling_rate = models.IntegerField(_('polling rate'), blank=True, null=True, default=15)

    class Meta:
        ordering = ['-last_checked',]
        verbose_name, verbose_name_plural = _('feed'), _('feeds')

    def __unicode__(self):
        return self.name

    def _get_absolute_url(self):
        return ('feed_detail', (), {})
    get_absolute_url = permalink(_get_absolute_url)

class TwitterAccount(models.Model):
    """A Twitter account is fed by multiple twitter feeds"""
    username = models.CharField(_('username'), blank=True,  max_length=80)
    password = models.CharField(_('password'), blank=True,  max_length=80)
    philter = models.CharField(_('filter'), help_text='Only messages containing this phrase will be passed on to the twitter account.  For multiple phrases, seperate them by a comma.', blank=True,  max_length=80)
    philter_replies = models.BooleanField(_('filter replies'), help_text="Tick this box to filter @replies automatically", default=True)
    minimum_datetime = models.DateTimeField(_('minimum datetime'), help_text='Do not smash tweets that occured before this date/time', blank=True, null=True)
    strip_tags = models.BooleanField(_('strip tags'), default=False)
    prepend_names = models.BooleanField(_('prepend names'), help_text="Tick this box to prepend the names of the individual twitter accounts to the smashed message", default=True)
    append_tags = models.BooleanField(_('append tags'), help_text="Take all tags and put them at the end", default=True)
    append_initials = models.BooleanField(_('append initials'), help_text="Append the author initials to the end", default = False)
 
    active = models.BooleanField(_('active'), default=True)
    feeds = models.ManyToManyField(Feed)