-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
models.py
83 lines (72 loc) · 2.97 KB
/
models.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
from django.db import models
from django.urls import reverse
from django.utils.translation import gettext_lazy as _
from mezzanine.conf import settings
from mezzanine.core.fields import FileField
from mezzanine.core.models import Displayable, Ownable, RichText, Slugged
from mezzanine.generic.fields import CommentsField, RatingField
from mezzanine.utils.models import AdminThumbMixin, upload_to
class BlogPost(Displayable, Ownable, RichText, AdminThumbMixin):
"""
A blog post.
"""
categories = models.ManyToManyField(
"BlogCategory",
verbose_name=_("Categories"),
blank=True,
related_name="blogposts",
)
allow_comments = models.BooleanField(verbose_name=_("Allow comments"), default=True)
comments = CommentsField(verbose_name=_("Comments"))
rating = RatingField(verbose_name=_("Rating"))
featured_image = FileField(
verbose_name=_("Featured Image"),
upload_to=upload_to("blog.BlogPost.featured_image", "blog"),
format="Image",
max_length=255,
null=True,
blank=True,
)
related_posts = models.ManyToManyField(
"self", verbose_name=_("Related posts"), blank=True
)
admin_thumb_field = "featured_image"
class Meta:
verbose_name = _("Blog post")
verbose_name_plural = _("Blog posts")
ordering = ("-publish_date",)
def get_absolute_url(self):
"""
URLs for blog posts can either be just their slug, or prefixed
with a portion of the post's publish date, controlled by the
setting ``BLOG_URLS_DATE_FORMAT``, which can contain the value
``year``, ``month``, or ``day``. Each of these maps to the name
of the corresponding urlpattern, and if defined, we loop through
each of these and build up the kwargs for the correct urlpattern.
The order which we loop through them is important, since the
order goes from least granular (just year) to most granular
(year/month/day).
"""
url_name = "blog_post_detail"
kwargs = {"slug": self.slug}
date_parts = ("year", "month", "day")
if settings.BLOG_URLS_DATE_FORMAT in date_parts:
url_name = "blog_post_detail_%s" % settings.BLOG_URLS_DATE_FORMAT
for date_part in date_parts:
date_value = str(getattr(self.publish_date, date_part))
if len(date_value) == 1:
date_value = "0%s" % date_value
kwargs[date_part] = date_value
if date_part == settings.BLOG_URLS_DATE_FORMAT:
break
return reverse(url_name, kwargs=kwargs)
class BlogCategory(Slugged):
"""
A category for grouping blog posts into a series.
"""
class Meta:
verbose_name = _("Blog Category")
verbose_name_plural = _("Blog Categories")
ordering = ("title",)
def get_absolute_url(self):
return reverse("blog_post_list_category", kwargs={"category": self.slug})