예제 #1
0
class TagsEntry(models.Model):
    """
    Abstract lodel class to add tags to the entries.
    """
    tags = TagField(_('tags'))

    @property
    def tags_list(self):
        """
        Return iterable list of tags.
        """
        return parse_tag_input(self.tags)

    class Meta:
        abstract = True
예제 #2
0
class Subject(models.Model):

    # nome
    name = models.CharField(max_length=64)

    # telefono
    phone_number = models.CharField(max_length=30)

    # email
    email = models.EmailField(blank='')

    # eta
    birthdate = models.DateField()

    # cv allegato
    cv = models.FileField(upload_to='/home/alessandro/Documenti',
                          null=True,
                          blank=True)

    locations = TagField()
    skills = TagField()
    targets = TagField()

    note = models.TextField(blank='')

    @property
    def age(self):
        date = datetime.datetime.now().date().year - self.birthdate.year
        return date

    def __unicode__(self):
        #return "%s, %s" %(self.name,self.email)
        return self.name

    def get_tags(self):
        return Tag.objects.get_for_object(self)
예제 #3
0
class Post(models.Model):
    title = models.CharField(verbose_name=u'Título', max_length=200)
    slug = models.SlugField(verbose_name=u'Slug', max_length=200)
    content = models.TextField(verbose_name=u'Conteúdo')
    pub_date = models.DateTimeField(verbose_name=u'Data de Publicação',
                                    auto_now_add=True)
    author = models.ForeignKey(User, verbose_name=u'Autor')
    tags = TagField(verbose_name=u'Tags')

    def __unicode__(self):
        return self.title

    class Meta:
        verbose_name = u'Post'
        ordering = ['-pub_date']
예제 #4
0
파일: models.py 프로젝트: hnbaoli/ddtcms
class News(models.Model):
	category       = models.ForeignKey(Category,null=True)
	deliverer      = models.ForeignKey(User,verbose_name='Deliverer',null=True,editable=True)
	source         = models.CharField(verbose_name='News Source',max_length=50,null=True,blank=True,help_text='Where the news comes from')
	title          = models.CharField(max_length=100)
	subtitle       = models.CharField(max_length=100,null=True,blank=True)
	slug           = models.SlugField(max_length=255,blank=True,unique=True,help_text='Automatically built From the title.')
	pub_date       = models.DateTimeField('date published',blank=True,default=datetime.datetime.now)
	content        = models.TextField()
	summary        = models.TextField(help_text="Summary",null=True,blank=True)
	tags           = TagField(help_text=tagfield_help_text, verbose_name=_('tags'))
	views          = models.PositiveIntegerField(_("Views"), default=0)
	comments       = models.PositiveIntegerField(_("Comments"), default=0)
	allow_comments = models.BooleanField(_("Allow Comments"),default=True)
	gallery        = models.ForeignKey(NewsPhotoGallery, unique=True, verbose_name=_('gallery'),related_name='gallery_news2',null=True,blank=True)
	approved       = models.BooleanField(_("Approved"),default=False)
	pic            = models.CharField('News Indicator Pic',max_length=200,null=True,blank=True,help_text="If has a pic url,show on homepage or indexpage")
	status         = models.PositiveIntegerField(_("Status"), choices=NEWS_STATUS, default=0)
	editor         = models.CharField(max_length=20,blank=True)


	objects = NewsManager()


	class Meta:
		ordering            = ('-pub_date',)
		unique_together     = (('slug', 'pub_date'), )
		get_latest_by       = 'pub_date'
		verbose_name        = _('News')
		verbose_name_plural = _('News')

	def get_absolute_url(self):
		if self.slug=="":
			return "/news/%s/" % self.id
		else:
			#return "/news/%s/%s/" % (self.pub_date.strftime("%Y/%b/%d").lower(), self.slug)
			return "/news/%s/%s/" % (self.pub_date.strftime("%Y/%m/%d").lower(), self.slug)

	def __unicode__(self):
		return self.title

	def get_previous(self):
		try:
			# isnull is to check whether it's published or not - drafts don't have dates, apparently
			return News.objects.all().filter(pub_date__lt=self.pub_date,pub_date__isnull=False)[0]
		except IndexError, e:
			# print 'Exception: %s' % e.message
			return None
예제 #5
0
class Snippet(models.Model):
    #Core Fields
    title = models.CharField(max_length=255)
    language = models.ForeignKey(Language)
    author = models.ForeignKey(User)
    description = models.TextField()
    description_html = models.TextField(editable=False)
    code = models.TextField()
    highlighted_code = models.TextField(editable=False)
    tags = TagField()
    pub_date = models.DateTimeField(editable=False)
    updated_date = models.DateTimeField(editable=False)
    #Custom Snippet Manager
    objects = managers.SnippetManager()

    class Meta:
        ordering = ['-pub_date']

    def __unicode__(self):
        return self.title

    def save(self, force_insert=False, force_update=False):
        """Override Django save method.
        """
        if not self.id:
            self.pub_date = datetime.datetime.now()
        self.updated_date = datetime.datetime.now()
        self.description_html = markdown(self.description)
        self.highlighted_code = self.highlight()
        super(Snippet, self).save(force_insert, force_update)

    def get_absolute_url(self):
        """Returns url for the request snippet object.
        """
        return "/snippets/%s/" % self.id

    def highlight(self):
        """Returns highlighted code from pygments.highlight
           It takes three arguments 
            1)Code to highlight
            2)Lexer to use
            3)Formatter to generate output
        """
        return highlight(self.code, self.language.get_lexer(),
                         formatters.HtmlFormatter(lineos=True))

    def get_tags(self):
        return Tag.objects.get_for_object(self)
예제 #6
0
class SurveyQuestion(Sortable):
    """This defines the question for survey

    **Attributes**:

        * ``question`` - survey name.
        * ``tags`` -
        * ``message_type`` -

    **Relationships**:

        * ``user`` - Foreign key relationship to the User model.\
        Each survey question is assigned to a User
        * ``surveyapp`` - Foreign key relationship to the SurveyApp model.\
        Each survey question is assigned to a SurveyApp
        * ``audio_message`` - Foreign key relationship to the AudioFile model.

    **Name of DB table**: survey_question
    """
    class Meta(Sortable.Meta):
        ordering = Sortable.Meta.ordering + ['surveyapp']

    question = models.CharField(
        max_length=500,
        verbose_name=_("Question"),
        help_text=_('Enter your question'))  # What is your preferred fruit?
    tags = TagField(blank=True, max_length=1000)
    user = models.ForeignKey('auth.User', related_name='Survey owner')
    surveyapp = models.ForeignKey(SurveyApp, verbose_name=_("SurveyApp"))

    audio_message = models.ForeignKey(AudioFile,
                                      null=True,
                                      blank=True,
                                      verbose_name=_("Audio File"))
    message_type = models.IntegerField(max_length=20,
                                       choices=MESSAGE_TYPE,
                                       default='1',
                                       blank=True,
                                       null=True,
                                       verbose_name=_('Message type'))

    created_date = models.DateTimeField(auto_now_add=True)
    updated_date = models.DateTimeField(auto_now=True)

    sortable_by = SurveyApp

    def __unicode__(self):
        return self.question
예제 #7
0
class Product(models.Model):
    categories = TreeForeignKey('Category', null=True, blank=True, on_delete=models.SET_NULL)
    # 카테고리 모델과 관계 만들기, 카테고리를 지워도 상품은 남아있어야함
    name = models.CharField(max_length=200, db_index=True)
    slug = models.SlugField(max_length=200, db_index=True, unique=True, allow_unicode=True)
    image = models.ImageField(upload_to='products/%Y/%m/%d', blank=True)
    image2 = models.ImageField(upload_to='products/%Y/%m/%d', blank=True, null=True)
    image3 = models.ImageField(upload_to='products/%Y/%m/%d', blank=True, null=True)
    image4 = models.ImageField(upload_to='products/%Y/%m/%d', blank=True, null=True)
    image5 = models.ImageField(upload_to='products/%Y/%m/%d', blank=True, null=True)
    description = models.TextField(blank=True)
    #meta_description = models.TextField(blank=True)
    tag_description = TagField(blank=True, null=True)

    price = models.DecimalField(max_digits=10, decimal_places=0) # 가격
    company = models.ForeignKey(Company, null=True, on_delete=models.SET_NULL)
    available_display = models.BooleanField('Display', default=True) # 상품 노출 여부
    available_order = models.BooleanField('Order', default=True) # 상품 주문 가능 여부
    count_order = models.IntegerField(default=0) # 팔린 갯수
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)

    count_order = models.IntegerField(default=0)
    sale_percent = models.IntegerField(default=0)

    recommend = models.BooleanField(default=False) #큐피드추천
    group = models.IntegerField(default=0)  #연관상품

    class Meta:
        ordering = ['-created']
        index_together = [['id', 'slug']] # 멀티 컬럼 색인 기능

    def __str__(self):
        return self.name

    def get_cat_list(self):  # for now ignore this instance method,
        k = self.category
        breadcrumb = ["dummy"]
        while k is not None:
            breadcrumb.append(k.slug)
            k = k.parent

        for i in range(len(breadcrumb) - 1):
            breadcrumb[i] = '/'.join(breadcrumb[-1:i - 1:-1])
        return breadcrumb[-1:0:-1]

    def get_absolute_url(self):
        return reverse('shop:product_detail', args=[self.id, self.slug])
예제 #8
0
class Trending(models.Model):
    LIVE_STATUS = 1
    DRAFT_STATUS = 2
    HIDDEN_STATUS = 3
    STATUS_CHOICES = ((LIVE_STATUS, 'Live'), (DRAFT_STATUS, 'Draft'),
                      (HIDDEN_STATUS, 'Hidden'))
    title = models.CharField(max_length=100, unique=False)
    excerpt = models.TextField(blank=True)
    body = models.TextField(blank=False)
    pub_date = models.DateField(default=datetime.now, blank=False)
    author = models.ForeignKey(User)
    enable_comments = models.BooleanField(default=True)
    featured = models.BooleanField(default=False)
    slug = models.SlugField(
        unique_for_date='pub_date',
        help_text=
        "Suggested value automatically generated ➥from title.Must be unique.")
    status = models.IntegerField(choices=STATUS_CHOICES, default=LIVE_STATUS)
    category = models.ManyToManyField(Category)
    tags = TagField()
    excerpt_html = models.TextField(editable=False, blank=True)
    body_html = models.TextField(editable=False, blank=True)
    #count=models.TextField(max_length=100, default=0)
    image1 = models.ImageField(upload_to='images',
                               verbose_name='Image',
                               blank=True)
    image2 = models.ImageField(upload_to='images',
                               verbose_name='Image',
                               blank=True)
    image3 = models.ImageField(upload_to='images',
                               verbose_name='Image',
                               blank=True)

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

    class Meta:
        ordering = ["-pub_date"]
        verbose_name_plural = "Trending"

    def __unicode__(self):
        return self.title

    def get_absolute_url(self):
        return (self.slug)
예제 #9
0
class BaseSimplePage(models.Model):

    # Basic Properties 
    name    = models.CharField( max_length=100, unique=True)                    # Used for reverse
    body    = models.TextField( )                                               # The page body
    markup  = models.CharField( max_length=2, choices=MARKUPS, default='HT' )   # Type of Markup
    created = models.DateTimeField( auto_now_add=True )                         # Created on
    updated = models.DateTimeField( auto_now=True )                             # Last Updated


    # Items for meta tags in the header
    title       = models.CharField( max_length=255, **blank )                   # The title tag
    author      = models.CharField( max_length=255, **blank )                   # meta name=author
    description = models.CharField( max_length=255, **blank )                   # meta name=description
    keywords    = TagField( )                                                   # meta name=keywords

    @property
    def keywords_list(self):
        """
        Return iterable list of tags.
        """
        return parse_tag_input(self.keywords)

    @property
    def to_html(self):
        mujump = {
            'MD': markdown,
            'TT': textile,
            'RE': restructuredtext,
        }

        if self.markup == 'HT': return self.body
        formatter = mujump[self.markup]
        return formatter(self.body)

    def __len__(self):
        return len(strip_tags(self.to_html).split())

    def __unicode__(self):
        if self.title: return self.title
        return u'%s: %s' % (self.name, self.updated.strftime("%c"))

    class Meta:
        abstract  = True
        app_label = 'simplepage'
        ordering  = ['-created', '-updated']
        verbose_name = 'page'
        verbose_name_plural = 'pages'
예제 #10
0
class License(models.Model):
    """Licenses under whose terms and conditions media is publicly accesible""" 

    name = models.CharField(max_length=255)
    link = models.URLField(unique=True)
    tags = TagField(help_text=_("family, comercial/non-commercial, etc."))

    class Meta:
        db_table = 'inline_media_licenses'

    def homepage(self):
        return '<a href="%s" target="_new">%s</a>' % tuple([self.link]*2)
    homepage.allow_tags = True

    def __unicode__(self):
        return self.name
예제 #11
0
class Post(models.Model):
    title = models.CharField('title', max_length=100, unique=True)
    slug = models.SlugField('slug')
    pub_date = models.DateTimeField('published date', default=datetime.now)
    tags = TagField(help_text='Separate tags with spaces, put quotes around multiple-word tags.', verbose_name='tags')
    content = models.TextField('post content')
    enable_comments = models.BooleanField(default=True)

    def get_absolute_url(self):
        return '/blog/%s/%s/' % (self.pub_date.strftime("%Y/%m/%d").lower(), self.slug)

    def blurb(self):
        return '%s...' % strip_tags(self.content)[:50]

    def __unicode__(self):
        return self.title
예제 #12
0
class Post(models.Model):
    pub_date = models.DateField()
    title = models.CharField(max_length=100, blank=True, null=True)
    text = models.TextField()
    image = models.FileField(null=True, blank=True, upload_to='contents')
    tag = TagField()

    class Meta:
        verbose_name = '포스'
        verbose_name_plural = '포스트'
        ordering = [
            'title',
        ]

    def __str__(self):
        return self.title
예제 #13
0
class Post(models.Model):
    category = models.ForeignKey(Category, on_delete=models.SET_NULL, blank=True, null=True)
    title = models.CharField(max_length=100)
    slug = models.SlugField(max_length=120, unique=True, allow_unicode=True, db_index=True)
    # text = RichTextUploadingField()
    text = models.TextField()
    material = models.FileField(upload_to='material/%Y/%m/%d', blank=True)
    tag = TagField(blank=True)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.title + " at " + self.created.strftime("%Y-%m-%d")

    def get_absolute_url(self):
        return resolve_url('post:post_detail', self.slug)
예제 #14
0
class Sensor(models.Model):
    name = models.CharField(max_length=40, blank=True,
                            help_text='Your name for the instrument. Example: "MicroImager" or "GeoCam"')
    make = models.CharField(max_length=40, blank=True,
                            help_text='The organization that makes the sensor.  Example: "Canon"')
    model = models.CharField(max_length=40, blank=True,
                             help_text='The model of sensor.  Example: "Droid" or "PowerShot G9"')
    software = models.CharField(max_length=160, blank=True,
                                help_text='Software running on the sensor, including any known firmware and version details. Example: "GeoCam Mobile 1.0.10, Android firmware 2.1-update1 build ESE81"')
    serialNumber = models.CharField(max_length=80, blank=True,
                                    verbose_name='serial number',
                                    help_text='Information that uniquely identifies this particular sensor unit. Example: "serialNumber:HT851N002808 phoneNumber:4126573579" ')
    notes = models.TextField(blank=True)
    tags = TagField(blank=True)
    uuid = UuidField()
    extras = ExtrasField(help_text="A place to add extra fields if we need them but for some reason can't modify the table schema.  Expressed as a JSON-encoded dict.")
예제 #15
0
class Photo(models.Model):
    photo = ImageField(upload_to="photos/photos/")
    privacy = models.CharField(choices = PRIVACY_CHOICES, max_length=30)
    notification_enabled = models.BooleanField(default=True)
    title = models.CharField(max_length=30)
    user = models.ForeignKey(User)
    description = models.TextField()
    #location = models.PointField(srid=SRID, blank=True)
    create_time = models.DateTimeField(auto_now_add=True)
    update_time = models.DateTimeField(auto_now=True)
    tags = TagField()
    objects = models.GeoManager()
    stats = models.ForeignKey(Stats, null=True, blank=True)
    info = models.ForeignKey(PhotoInfo, null=True, blank=True)
    def __unicode__(self):
        return self.title
예제 #16
0
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)
예제 #17
0
class Post(models.Model):
    title = models.CharField(max_length='200')
    body = models.TextField()
    approved = models.BooleanField(default=False, blank=True)

    date = models.DateTimeField('date', blank=True, default=datetime.now())
    tags = TagField()

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

    def __unicode__(self):
        return self.title

    def get_absolute_url(self):
        return "http://openwatch.net/blog/" + str(self.pk)
예제 #18
0
파일: models.py 프로젝트: realek3321/ch10
class Post(models.Model):
    # 아래에서 관리자 화면의 레이블과 도움말은 모두 한글로 수정하였음(교과서에서는 대문자 영문이었음)
    # 한 줄로 입력되는 CharField
    title = models.CharField('제목', max_length=50)
    slug = models.SlugField(
        '슬러그',  # 기본 길이 50, 인덱스가 기본 생성됨,
        # 제목에서 주요 단어를 하으픈으로 연결하여 생성
        unique=True,  # unique 설정, 기본키 대용으로 사용 가능
        allow_unicode=True,  # 한글 입력 가능하도록
        help_text='제목에 대한 한 단어의 별명.')
    description = models.CharField(
        '설명',
        max_length=100,
        blank=True,  # 블랭크 허용
        help_text='간략한 설명 문구.')
    content = models.TextField('내용')  # TextField이므로 여러 줄 입력 가능함
    create_date = models.DateTimeField('최초 생성 일시',
                                       auto_now_add=True)  # 최초 생성 일시를 자동 저장하도록
    modify_date = models.DateTimeField('최종 수정 일시',
                                       auto_now=True)  # 최종 수정 일시를 자동 저장하도록
    tag = TagField(
        '태그',  # ch07 추가
        help_text='게시글에 대한 태그')  # ch07 추가

    class Meta:

        # 필드 속성 외에 필요한 파라미터를 Meta 내부 클래스로 정의
        verbose_name = '기사'  # 'post'
        verbose_name_plural = '기사 모음'  # 'posts'
        db_table = 'my_posts'  # DB에 저장할 테이블 이름을 my_posts'라고 지정
        # 기본값(앱이름_모델클래스이름)은 'blog_post'
        ordering = ('-modify_date', )  # 최종 수정 일시의 내림차순 정렬

    def __str__(self):
        return self.title  # 객체를 출력할 때 제목만 출력

    def get_absolute_url(self):  # 이 메소드가 정의된 객체를 지칭하는 URL을 반환
        # 아래에서 'blog:post_detail'는 blog 앱 이름공간의 post_detail이란 의미
        # # Example: /post/django-example/
        # url(r'^post/(?P<slug>[-\w]+)/$', PostDV.as_view(), name='post_detail'),
        return reverse('blog:post_detail', args=(self.slug, ))

    def get_previous_post(self):  # 3.2.5 항에서 템플릿 작성할 때 사용
        return self.get_previous_by_modify_date()

    def get_next_post(self):  # 3.2.5 항에서 템플릿 작성할 때 사용
        return self.get_next_by_modify_date()
예제 #19
0
class Question(models.Model):
    def __unicode__(self):
        return self.content

    def get_absolute_url(self):
        return reverse('question-detail', kwargs={'question_id': str(self.id)})

    def answers_shuffled(self):
        return self.answer_set.order_by('?')

    def set_tags(self, tags):
        Tag.objects.update_tags(self, tags)

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

    def update_sq(self):
        # Get all user's attempts at this question
        # Final Max('usq') is just to rename value, not possible to rename on values bit, which sucks
        end_date = datetime.datetime.now()
        start_date = end_date - settings.SQ_CALCULATE_HISTORY

        data = self.userquestionattempt_set.filter(
            created__range=(start_date, end_date)).values('user_sq').annotate(
                n=Count('id'), y=Avg('percent_correct'), x=Max('user_sq'))
        self.sq = sq_calculate(data, 'asc')  # Ascending data set
        self.save()

    def update_ttc(self):
        ttc = self.userquestionattempt_set.aggregate(Avg('time_to_complete'))
        if ttc:
            self.time_to_complete = min(
                ttc['time_to_complete__avg'],
                QUESTION_TTC_MINIMUM)  # Minimum 5 seconds per question
            self.save()

    content = models.TextField()

    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)

    tags = TagField()
    author = models.ForeignKey(User)
    sq = models.IntegerField(blank=True, null=True, editable=False)

    # Auto-populated from averages of all user attempts (total seconds taken)
    time_to_complete = models.IntegerField(default=15)  #, editable = False )
예제 #20
0
class Entry(models.Model):
    LIVE_STATUS = 1
    DRAFT_STATUS = 2
    HIDDEN_STATUS = 3
    STATUS_CHOICES = (
        (LIVE_STATUS, 'Live'),
        (DRAFT_STATUS, 'Draft'),
        (HIDDEN_STATUS, 'Hidden'),
    )
    status = models.IntegerField(choices=STATUS_CHOICES, default=LIVE_STATUS)
    live = LiveEntryManager()
    objects = models.Manager()
    title = models.CharField(max_length=250)
    excerpt = models.TextField(blank=True)
    body = models.TextField()
    pub_date = models.DateTimeField(default=datetime.datetime.now)
    slug = models.SlugField(unique_for_date='pub_date')
    author = models.ForeignKey(User)
    enable_comments = models.BooleanField(default=True)
    featured = models.BooleanField(default=False)
    categories = models.ManyToManyField(Category)
    tags = TagField()

    excerpt_html = models.TextField(editable=False, blank=True)
    body_html = models.TextField(editable=False, blank=True)

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

    def __unicode__(self):
        return self.title

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

    @models.permalink
    def get_absolute_url(self):
        return ('coltrane_entry_object_detail', (), {
            'year': self.pub_date.strftime("%Y"),
            'month': self.pub_date.strftime("%b").lower(),
            'day': self.pub_date.strftime("%d"),
            'slug': self.slug
        })
예제 #21
0
class Bookmark(models.Model, DiffingMixin):
    url = models.URLField()
    title = models.CharField(max_length=1024)
    domain = models.CharField(max_length=128,
                              blank=True,
                              null=True,
                              db_index=True)
    note = models.TextField(null=True, blank=True)
    tags = TagField()

    created_time = models.DateTimeField(db_index=True)
    modified_time = models.DateTimeField(auto_now=True, db_index=True)
    unique_key = models.CharField(max_length=32)
    user = models.ForeignKey(User, related_name="bookmarks")
    list = models.ForeignKey(List, null=True, blank=True)
    charset = models.CharField(null=True, max_length=10)

    objects = BookmarkManager()

    def tags_splited(self):
        return self.tags.split(" ")

    @property
    def favicon(self):
        return reverse("service_favicon") + u"?url=" + self.url
        #return 'https://icons.duckduckgo.com/ip2/{}.ico'.format(self.domain)
        #return 'http://g.etfv.co/http://{}?defaulticon=lightpng'.format(self.domain)
        #return 'https://s2.googleusercontent.com/s2/favicons?alt=site&domain={}'.format(self.domain)

    def absolute_url(self):
        return reverse('bookmark_detail', args=[self.id])

    @property
    def screenshot_image(self):
        from screenshot.models import Screenshot
        image = ''
        if self.domain == 'note.lianpeng.me':
            image = settings.STATIC_URL + 'img/note_placeholder.png'
        else:
            try:
                image = get_thumbnail(self.screenshot.image,
                                      '140x100',
                                      crop='center',
                                      quality=99).url
            except Screenshot.DoesNotExist, e:
                pass
            except:
예제 #22
0
class Quote(Post):
    """Quote model"""

    title = models.CharField(max_length=100, blank=False, null=False)
    slug = models.SlugField(max_length=255, unique=True)
    markup = MarkupField(default="markdown")
    body = TextFieldWithInlines()
    body_markup = models.TextField(editable=True, blank=True, null=True)
    quote_author = models.CharField(blank=False,
                                    null=False,
                                    max_length=255,
                                    help_text=_("quote's author"))
    url_source = models.URLField(blank=True, null=True)
    tags = TagField()
    objects = PostManager()

    class Meta:
        verbose_name = _("quote")
        verbose_name_plural = _("quotes")
        db_table = "dress_blog_quotes"
        ordering = ("-pub_date", )
        get_latest_by = "pub_date"

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

    def save(self, *args, **kwargs):
        self.body_markup = mark_safe(
            formatter(self.body, filter_name=self.markup))
        super(Quote, self).save(*args, **kwargs)

    @permalink
    def get_absolute_url(self):
        kwargs = {
            "year": self.pub_date.year,
            "month": self.pub_date.strftime("%b").lower(),
            "day": self.pub_date.day,
            "slug": self.slug
        }
        if self.status == 1:
            return ("blog-quote-detail-draft", None, kwargs)
        if self.status == 2:
            return ("blog-quote-detail-review", None, kwargs)
        elif self.pub_date > now():
            return ("blog-quote-detail-upcoming", None, kwargs)
        else:
            return ("blog-quote-detail", None, kwargs)
예제 #23
0
class Post(models.Model):
    """Post model."""
    STATUS_CHOICES = (
        (1, _('Draft')),
        (2, _('Public')),
    )
    thumb = ImageWithThumbnailsField(upload_to='blogposts',
        thumbnail={'size': (200, 200), 'options': ('crop',)},
        blank=True, null=True, help_text=_('Thumbnail'))
    title = models.CharField(_('title'), max_length=200)
    slug = models.SlugField(_('slug'), unique_for_date='publish')
    author = models.ForeignKey(User, blank=True, null=True)
    body = models.TextField(_('body'), )
    tease = models.TextField(_('tease'), blank=True, help_text=_('Concise text suggested. Does not appear in RSS feed.'))
    status = models.IntegerField(_('status'), choices=STATUS_CHOICES, default=2)
    allow_comments = models.BooleanField(_('allow comments'), default=False, editable=False)
    publish = models.DateTimeField(_('publish'), default=datetime.datetime.now)
    created = models.DateTimeField(_('created'), auto_now_add=True)
    modified = models.DateTimeField(_('modified'), auto_now=True)
    categories = models.ManyToManyField(Category, blank=True)
    tags = TagField()
    objects = PublicManager()

    class Meta:
        verbose_name = _('post')
        verbose_name_plural = _('posts')
        db_table  = 'blog_posts'
        ordering  = ('-publish',)
        get_latest_by = 'publish'

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

    @permalink
    def get_absolute_url(self):
        return ('blog_detail', None, {
            'year': self.publish.year,
            'month': self.publish.strftime('%b').lower(),
            'day': self.publish.day,
            'slug': self.slug
        })

    def get_previous_post(self):
        return self.get_previous_by_publish(status__gte=2)

    def get_next_post(self):
        return self.get_next_by_publish(status__gte=2)
예제 #24
0
class Recipe(models.Model):
    name = models.CharField(max_length=255)
    slug = models.SlugField()
    servings = models.IntegerField(
        blank=True,
        null=True,
        help_text='How many people might this recipe serve? Optional.')
    prep_time = models.IntegerField(blank=True,
                                    null=True,
                                    help_text='In minutes. Optional.')
    cook_time = models.IntegerField(blank=True,
                                    null=True,
                                    help_text='In minutes. Optional.')
    directions = models.TextField()
    date_added = models.DateTimeField(default=datetime.datetime.now)
    user = models.ForeignKey(User, blank=True, null=True)
    photos = models.ManyToManyField(Photo, blank=True, null=True)
    main_photos = models.ManyToManyField(Photo,
                                         blank=True,
                                         null=True,
                                         related_name='main_photos')
    is_public = models.BooleanField(default=True)
    creates_ingredient = models.ForeignKey(Ingredient, blank=True, null=True)
    source = models.TextField(
        blank=True,
        null=True,
        help_text='Where or from whom did you get this recipe? Optional.')
    notes = models.TextField(blank=True, null=True, help_text='Optional.')
    tags = TagField(
        help_text=
        'Enclose multi word tags in double quotes and use commas to separate tags. Optional.'
    )
    tools = models.ManyToManyField(KitchenTool, blank=True, null=True)

    class Meta:
        ordering = ['-date_added']

    def __unicode__(self):
        return self.name

    @property
    def average_rating(self):
        ratings = self.ratings.all()
        if ratings:
            return sum([rating.rating for rating in ratings]) / len(ratings)
        else:
            return 0
예제 #25
0
class Article(ArticlePageMixin):
    category = models.ManyToManyField(Category, verbose_name='Категория')
    name = models.CharField(max_length=128,
                            verbose_name='Название',
                            db_index=True)
    short_post = models.TextField(verbose_name='Краткое описание')
    full_post = models.TextField(verbose_name='Полное описание')
    date = models.DateTimeField(verbose_name='Дата', default=timezone.now)
    slug_cat_unique = models.SlugField(db_index=True, blank=True)
    thumb = models.ImageField(upload_to='images/%Y/%m/%d/thumb/',
                              blank=True,
                              null=True,
                              verbose_name='Изображение',
                              editable=True)
    tags = TagField(blank=True)
    likes = models.IntegerField(default=0, db_index=True, blank=True)

    def _create_tags(self):
        """Create tags from name of article"""
        words = re.split('\W+', self.name)
        words = list(filter(lambda word: len(word) > 3, words))
        return " ".join(words).lower()

    def save(self, *args, **kwargs):
        """If tags not determinated then generating their"""
        if not self.tags:
            tags = self._create_tags()
            if tags:
                self.tags = self._create_tags()
        """If no set meta-parameters html - title or description then
        generate their"""
        if not self.title_meta:
            self.title_meta = self._generate_metatags(self.name, 55)
        if not self.description_meta:
            self.description_meta = \
                self._generate_metatags(self.full_post, 100)

        super().save(*args, **kwargs)
        """Resize image"""
        if self.thumb:
            THUMB_WIDTH = getattr(settings, 'THUMB_WIDTH', 150)
            THUMB_HEIGHT = getattr(settings, 'THUMB_HEIGHT', 225)
            self._resize_thumb(THUMB_WIDTH, THUMB_HEIGHT)

    class Meta:
        verbose_name = 'Статья'
        verbose_name_plural = 'Статьи'
예제 #26
0
class Task(models.Model):
    """
    Модель для задачи
    """
    tags = TagField(verbose_name='Теги')

    section = models.ForeignKey(Section,
                                related_name='section',
                                verbose_name='Раздел',
                                on_delete=models.CASCADE)  # основной раздел
    subsection = models.ForeignKey(Subsection,
                                   related_name='subsection',
                                   verbose_name='Подраздел',
                                   on_delete=models.CASCADE)  # подраздел

    grades = models.ManyToManyField(
        Grade, blank=True, verbose_name='Классы')  # классы для данной задачи

    tex_used = models.BooleanField(default=False, verbose_name='TeX')

    def __str__(self):
        return f'Задача {str(self.pk)}'

    def name(self):
        return str(self)

    name.short_description = 'Task name'
    name.admin_order_field = 'pk'

    def has_tip(self):
        return any(section.is_tip for section in self.tasksection_set.all())

    has_tip.boolean = True
    has_tip.short_description = 'Tip'

    def has_solution(self):
        return any(section.is_solution
                   for section in self.tasksection_set.all())

    has_solution.boolean = True
    has_solution.short_description = 'Solution'

    def has_answer(self):
        return any(section.is_answer for section in self.tasksection_set.all())

    has_answer.boolean = True
    has_answer.short_description = 'Answer'
예제 #27
0
파일: models.py 프로젝트: Alsum/djangoblog
class Entry(models.Model):

    title = models.CharField(max_length=200)

    slug = models.SlugField(unique_for_date='pub_date',
                            help_text='Automatically built from the title.')

    body_html = models.TextField(blank=True)

    body_markdown = models.TextField(
    )  #note, if you're using Markdown, include this field, otherwise just go with body_html

    pub_date = models.DateTimeField('Date published')

    tags = TagField()

    enable_comments = models.BooleanField(default=True)

    PUB_STATUS = (
        (0, 'Draft'),
        (1, 'Published'),
    )

    status = models.IntegerField(choices=PUB_STATUS, default=0)

    class Meta:

        ordering = ('-pub_date', )

        get_latest_by = 'pub_date'

        verbose_name_plural = 'entries'

    def __unicode__(self):

        return u'%s' % (self.title)

    def get_absolute_url(self):

        return "/%s/%s/" % (self.pub_date.strftime("%Y/%b/%d").lower(),
                            self.slug)

    def save(self):

        self.body_html = markdown.markdown(self.body_markdown, safe_mode=False)

        super(Entry, self).save()
예제 #28
0
class Photo(ImageModel):
    title = models.CharField(_('title'), max_length=100, unique=True)
    title_slug = models.SlugField(_('slug'), unique=True,
                                  help_text=('A "slug" is a unique URL-friendly title for an object.'))
    caption = models.TextField(_('caption'), blank=True)
    date_added = models.DateTimeField(_('date added'), default=datetime.now, editable=False)
    is_public = models.BooleanField(_('is public'), default=True, help_text=_('Public photographs will be displayed in the default views.'))
    tags = TagField(help_text=tagfield_help_text, verbose_name=_('tags'))

    class Meta:
        ordering = ['-date_added']
        get_latest_by = 'date_added'
        verbose_name = _("photo")
        verbose_name_plural = _("photos")

    def __unicode__(self):
        return self.title

    def __str__(self):
        return self.__unicode__()

    def save(self, *args, **kwargs):
        if self.title_slug is None:
            self.title_slug = slugify(self.title)
        super(Photo, self).save(*args, **kwargs)

    def get_absolute_url(self):
        return reverse('pl-photo', args=[self.title_slug])

    def public_galleries(self):
        """Return the public galleries to which this photo belongs."""
        return self.galleries.filter(is_public=True)

    def get_previous_in_gallery(self, gallery):
        try:
            return self.get_previous_by_date_added(galleries__exact=gallery,
                                                   is_public=True)
        except Photo.DoesNotExist:
            return None

    def get_next_in_gallery(self, gallery):
        try:
            return self.get_next_by_date_added(galleries__exact=gallery,
                                               is_public=True)
        except Photo.DoesNotExist:
            return None
예제 #29
0
class Lab(models.Model):
    """
	** Lab **
	
	Lab Class define all fields required to submit detail about a LAB 
	of a Department.
	
	"""
    name = models.CharField(max_length=300)
    department = models.ForeignKey(Department)
    tags = TagField()

    def __unicode__(self):
        return self.name

    def get_tags(self):
        return Tag.objects.get_for_object(self)
예제 #30
0
class BaseImage(models.Model):
    class Meta(object):
        abstract = True
        ordering = ('order', 'id')
        permissions = (('moderate_images',
                        'View, update and delete any image'), )

    title = models.CharField(_('Title'), max_length=255, blank=True, null=True)
    description = models.TextField(_('Description'), blank=True, null=True)
    tags = TagField(_('Tags'), blank=True)
    order = models.IntegerField(_('Order'), default=0)
    image = ImageField(verbose_name=_('File'),
                       max_length=255,
                       upload_to=FilePathGenerator(to=UPLOAD_TO))
    user = models.ForeignKey(get_user_model_name(),
                             verbose_name=_('User'),
                             null=True,
                             blank=True,
                             related_name='images')
    created = models.DateTimeField(_('Created'), auto_now_add=True, null=True)
    updated = models.DateTimeField(_('Updated'), auto_now=True, null=True)
    album = models.ForeignKey(swapper.get_model_name('imagestore', 'Album'),
                              verbose_name=_('Album'),
                              null=True,
                              blank=True,
                              related_name='images')

    @permalink
    def get_absolute_url(self):
        return 'imagestore:image', (), {'pk': self.id}

    def __str__(self):
        return '%s' % self.id

    def admin_thumbnail(self):
        try:
            return '<img src="%s">' % get_thumbnail(
                self.image, '100x100', crop='center').url
        except IOError:
            logger.exception('IOError for image %s', self.image)
            return 'IOError'
        except ThumbnailError as ex:
            return 'ThumbnailError, %s' % ex.message

    admin_thumbnail.short_description = _('Thumbnail')
    admin_thumbnail.allow_tags = True