diff options
Diffstat (limited to 'app/posts')
23 files changed, 1177 insertions, 0 deletions
diff --git a/app/posts/__init__.py b/app/posts/__init__.py new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/app/posts/__init__.py diff --git a/app/posts/admin.py b/app/posts/admin.py new file mode 100644 index 0000000..ad8f509 --- /dev/null +++ b/app/posts/admin.py @@ -0,0 +1,103 @@ +from django.contrib import admin +from django import forms +from django.contrib.gis.admin import OSMGeoAdmin +from django.contrib.contenttypes.admin import GenericStackedInline + +from utils.widgets import AdminImageWidget, LGEntryForm +from .models import Post + +from photos.forms import GalleryForm +from photos.models import LuxImage +from utils.util import get_latlon + + +@admin.register(Post) +class EntryAdmin(OSMGeoAdmin): + form = LGEntryForm + + def get_queryset(self, request): + test_model_qs = super(EntryAdmin, self).get_queryset(request) + test_model_qs = test_model_qs.prefetch_related('related').prefetch_related('books') + + return test_model_qs + + def render_change_form(self, request, context, *args, **kwargs): + #context['adminform'].form.fields['featured_image'].queryset = LuxImage.objects.all()[:200] + return super(EntryAdmin, self).render_change_form(request, context, *args, **kwargs) + + def formfield_for_dbfield(self, db_field, **kwargs): + if db_field.name == 'thumbnail' or db_field.name == 'image': + field = forms.FileField(widget=AdminImageWidget) + elif db_field.name == 'meta_description': + field = forms.CharField(widget=forms.Textarea(attrs={'rows': 4, 'cols': 75})) + field.required = False + else: + field = super(EntryAdmin, self).formfield_for_dbfield(db_field, **kwargs) + return field + + list_display = ('title', 'post_type', 'pub_date', 'template_name', 'status', 'category') + search_fields = ['title', 'body_markdown'] + prepopulated_fields = {"slug": ('title',)} + list_filter = ('pub_date', 'enable_comments', 'status', 'category') + filter_horizontal = ('related',) + fieldsets = ( + ('Entry', { + 'fields': ( + 'title', + 'subtitle', + 'body_markdown', + ('pub_date', 'status', 'post_type', 'old_id',), + 'slug', + ), + 'classes': ( + 'show', + 'extrapretty', + 'wide' + ) + } + ), + ('Metadata', { + 'fields': ( + 'point', + 'dek', + 'meta_description', + ('category', 'tags'), + 'template_name', + 'enable_comments', + 'featured_image', + 'related', + ('has_video', 'disclaimer',), + ), + }), + ('Extras', { + 'fields': ( + 'books', + 'field_notes', + 'jrnl', + 'prologue_markdown', + 'epilogue_markdown', + 'originally_published_by', + 'originally_published_by_url', + ), + }), + ) + # options for OSM map Using custom ESRI topo map + lat, lon = get_latlon() + default_lon = lon + default_lat = lat + default_zoom = 10 + units = True + scrollable = False + map_width = 700 + map_height = 425 + map_template = 'gis/admin/osm.html' + openlayers_url = '/static/admin/js/OpenLayers.js' + + class Media: + js = ('image-loader.js', 'next-prev-links.js') + css = { + "all": ("my_styles.css",) + } + + + diff --git a/app/posts/build.py b/app/posts/build.py new file mode 100644 index 0000000..5cf552b --- /dev/null +++ b/app/posts/build.py @@ -0,0 +1,27 @@ +from django.urls import reverse +from django.apps import apps +from builder.base import BuildNew +from itertools import chain + +from django.conf import settings + + +class BuildPosts(BuildNew): + + def build(self): + self.build_list_view( + base_path=reverse("essay-list:list"), + paginate_by=50 + ) + self.build_list_view( + base_path=reverse("guide-list:list"), + paginate_by=50 + ) + self.build_detail_view() + + + + +def posts_builder(): + j = BuildPosts("posts", "post") + j.build() diff --git a/app/posts/essay_urls.py b/app/posts/essay_urls.py new file mode 100644 index 0000000..ea7777d --- /dev/null +++ b/app/posts/essay_urls.py @@ -0,0 +1,29 @@ +from django.urls import path, re_path + +from . import views + +app_name = "essays" + +urlpatterns = [ + path( + r'<str:slug>', + views.PostDetailView.as_view(), + name="detail" + ), + path( + r'<str:slug>.txt', + views.PostDetailViewTXT.as_view(), + name="detail-txt" + ), + path( + r'<int:page>/', + views.EssayListView.as_view(), + name="list" + ), + path( + r'', + views.EssayListView.as_view(), + {'page':1}, + name="list" + ), +] diff --git a/app/posts/guide_urls.py b/app/posts/guide_urls.py new file mode 100644 index 0000000..d43d76a --- /dev/null +++ b/app/posts/guide_urls.py @@ -0,0 +1,29 @@ +from django.urls import path, re_path + +from . import views + +app_name = "guides" + +urlpatterns = [ + path( + r'<str:slug>', + views.PostDetailView.as_view(), + name="detail" + ), + path( + r'<str:slug>.txt', + views.PostDetailViewTXT.as_view(), + name="detail-txt" + ), + path( + r'<int:page>/', + views.GuidesListView.as_view(), + name="list" + ), + path( + r'', + views.GuidesListView.as_view(), + {'page':1}, + name="list" + ), +] diff --git a/app/posts/importer.py b/app/posts/importer.py new file mode 100644 index 0000000..53a84aa --- /dev/null +++ b/app/posts/importer.py @@ -0,0 +1,29 @@ +for e in essaysold: + if e.featured_image: + feat = e.featured_image + else: + feat = None + if e.meta_description: + meta = e.meta_description + else: + meta = "need meta" + new, created = Post.objects.get_or_create( + old_id=e.pk, + post_type=2, + title=e.title, + subtitle=e.sub_title, + dek=e.dek, + slug=e.slug, + prologue_markdown=e.preamble, + body_markdown=e.body_markdown, + pub_date=e.pub_date, + enable_comments=e.enable_comments, + status=e.status, + meta_description=meta, + originally_published_by=e.originally_published_by, + originally_published_by_url=e.originally_published_by_url, + featured_image=feat, + has_video=e.has_video, + epilogue_markdown=e.afterword, + ) + print(created) diff --git a/app/posts/migrations/0001_initial.py b/app/posts/migrations/0001_initial.py new file mode 100644 index 0000000..e853a06 --- /dev/null +++ b/app/posts/migrations/0001_initial.py @@ -0,0 +1,65 @@ +# Generated by Django 2.1.7 on 2019-09-17 17:53 + +import django.contrib.gis.db.models.fields +from django.db import migrations, models +import django.db.models.deletion +import taggit.managers + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ('jrnl', '0044_auto_20190917_1703'), + ('books', '0009_book_afflink'), + ('normalize', '__first__'), + ('taxonomy', '0001_initial'), + ('locations', '0018_auto_20190414_2124'), + ('fieldnotes', '0002_auto_20190303_1222'), + ('photos', '0019_auto_20190704_0903'), + ] + + operations = [ + migrations.CreateModel( + name='Post', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('title', models.CharField(max_length=200)), + ('subtitle', models.CharField(blank=True, max_length=200)), + ('slug', models.SlugField(unique_for_date='pub_date')), + ('prologue_markdown', models.TextField(blank=True)), + ('prologue_html', models.TextField(blank=True)), + ('body_markdown', models.TextField()), + ('body_html', models.TextField(blank=True)), + ('epilogue_markdown', models.TextField(blank=True)), + ('epilogue_html', models.TextField(blank=True)), + ('dek', models.TextField(blank=True, null=True)), + ('meta_description', models.CharField(blank=True, max_length=256, null=True)), + ('pub_date', models.DateTimeField(verbose_name='Date published')), + ('last_updated', models.DateTimeField(auto_now=True)), + ('enable_comments', models.BooleanField(default=False)), + ('status', models.IntegerField(choices=[(0, 'Draft'), (1, 'Published')], default=0)), + ('post_type', models.IntegerField(choices=[(0, 'guide'), (1, 'review'), (2, 'essay')], default=0)), + ('template_name', models.IntegerField(choices=[(0, 'single')], default=0)), + ('has_video', models.BooleanField(blank=True, default=False)), + ('disclaimer', models.BooleanField(blank=True, default=True)), + ('point', django.contrib.gis.db.models.fields.PointField(blank=True, null=True, srid=4326)), + ('originally_published_by', models.CharField(blank=True, max_length=400)), + ('originally_published_by_url', models.CharField(blank=True, max_length=400)), + ('books', models.ManyToManyField(blank=True, to='books.Book')), + ('category', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='taxonomy.Category')), + ('featured_image', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='photos.LuxImage')), + ('field_notes', models.ManyToManyField(blank=True, to='fieldnotes.FieldNote')), + ('jrnl', models.ManyToManyField(blank=True, to='jrnl.Entry')), + ('location', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='locations.Location')), + ('related', models.ManyToManyField(blank=True, to='normalize.RelatedPost')), + ('tags', taggit.managers.TaggableManager(blank=True, help_text='Topics Covered', through='taxonomy.TaggedItems', to='taxonomy.LuxTag', verbose_name='Tags')), + ], + options={ + 'ordering': ('-pub_date',), + 'get_latest_by': 'pub_date', + 'verbose_name_plural': 'entries', + }, + ), + ] diff --git a/app/posts/migrations/0002_auto_20190917_2029.py b/app/posts/migrations/0002_auto_20190917_2029.py new file mode 100644 index 0000000..c6f77eb --- /dev/null +++ b/app/posts/migrations/0002_auto_20190917_2029.py @@ -0,0 +1,22 @@ +# Generated by Django 2.1.7 on 2019-09-17 20:29 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('posts', '0001_initial'), + ] + + operations = [ + migrations.AlterModelOptions( + name='post', + options={'get_latest_by': 'pub_date', 'ordering': ('-pub_date',)}, + ), + migrations.AddField( + model_name='post', + name='old_id', + field=models.IntegerField(blank=True, null=True), + ), + ] diff --git a/app/posts/migrations/0003_auto_20190918_1230.py b/app/posts/migrations/0003_auto_20190918_1230.py new file mode 100644 index 0000000..d7c89a8 --- /dev/null +++ b/app/posts/migrations/0003_auto_20190918_1230.py @@ -0,0 +1,54 @@ +# Generated by Django 2.1.7 on 2019-09-18 12:30 + +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + dependencies = [ + ('posts', '0002_auto_20190917_2029'), + ] + + operations = [ + migrations.AlterField( + model_name='post', + name='epilogue_html', + field=models.TextField(blank=True, null=True), + ), + migrations.AlterField( + model_name='post', + name='epilogue_markdown', + field=models.TextField(blank=True, null=True), + ), + migrations.AlterField( + model_name='post', + name='featured_image', + field=models.ForeignKey(blank=True, on_delete=django.db.models.deletion.CASCADE, to='photos.LuxImage'), + ), + migrations.AlterField( + model_name='post', + name='meta_description', + field=models.CharField(blank=True, max_length=256), + ), + migrations.AlterField( + model_name='post', + name='originally_published_by', + field=models.CharField(blank=True, max_length=400, null=True), + ), + migrations.AlterField( + model_name='post', + name='originally_published_by_url', + field=models.CharField(blank=True, max_length=400, null=True), + ), + migrations.AlterField( + model_name='post', + name='prologue_html', + field=models.TextField(blank=True, null=True), + ), + migrations.AlterField( + model_name='post', + name='prologue_markdown', + field=models.TextField(blank=True, null=True), + ), + ] diff --git a/app/posts/migrations/0004_auto_20190918_1241.py b/app/posts/migrations/0004_auto_20190918_1241.py new file mode 100644 index 0000000..da829ad --- /dev/null +++ b/app/posts/migrations/0004_auto_20190918_1241.py @@ -0,0 +1,19 @@ +# Generated by Django 2.1.7 on 2019-09-18 12:41 + +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + dependencies = [ + ('posts', '0003_auto_20190918_1230'), + ] + + operations = [ + migrations.AlterField( + model_name='post', + name='featured_image', + field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='photos.LuxImage'), + ), + ] diff --git a/app/posts/migrations/0005_auto_20190918_1244.py b/app/posts/migrations/0005_auto_20190918_1244.py new file mode 100644 index 0000000..0cc59a8 --- /dev/null +++ b/app/posts/migrations/0005_auto_20190918_1244.py @@ -0,0 +1,19 @@ +# Generated by Django 2.1.7 on 2019-09-18 12:44 + +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + dependencies = [ + ('posts', '0004_auto_20190918_1241'), + ] + + operations = [ + migrations.AlterField( + model_name='post', + name='category', + field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='taxonomy.Category'), + ), + ] diff --git a/app/posts/migrations/__init__.py b/app/posts/migrations/__init__.py new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/app/posts/migrations/__init__.py diff --git a/app/posts/models.py b/app/posts/models.py new file mode 100644 index 0000000..1e1da1e --- /dev/null +++ b/app/posts/models.py @@ -0,0 +1,200 @@ +import datetime +import os + +from django.dispatch import receiver +from django.contrib.gis.db import models +from django.db.models.signals import post_save +from django.contrib.contenttypes.fields import GenericRelation, GenericForeignKey +from django.contrib.contenttypes.models import ContentType +from django.urls import reverse +from django.utils.functional import cached_property +from django.apps import apps +from django.conf import settings +from django.contrib.sitemaps import Sitemap +from django import forms + +import urllib.request +import urllib.parse +import urllib.error +from django_gravatar.helpers import get_gravatar_url, has_gravatar, calculate_gravatar_hash +from django_comments.signals import comment_was_posted +from django_comments.models import Comment +from django_comments.moderation import CommentModerator, moderator + +from taggit.managers import TaggableManager + +from normalize.models import RelatedPost +from photos.models import LuxImage, LuxImageSize +from locations.models import Location +from books.models import Book +from fieldnotes.models import FieldNote +from taxonomy.models import TaggedItems, Category +from jrnl.models import Entry +from utils.util import render_images, parse_video, markdown_to_html + + +class Post(models.Model): + old_id = models.IntegerField(blank=True, null=True) + title = models.CharField(max_length=200) + subtitle = models.CharField(max_length=200, blank=True) + slug = models.SlugField(unique_for_date='pub_date') + prologue_markdown = models.TextField(blank=True, null=True) + prologue_html = models.TextField(blank=True, null=True) + body_markdown = models.TextField() + body_html = models.TextField(blank=True) + epilogue_markdown = models.TextField(blank=True, null=True) + epilogue_html = models.TextField(blank=True, null=True) + dek = models.TextField(null=True, blank=True) + meta_description = models.CharField(max_length=256, blank=True) + pub_date = models.DateTimeField('Date published') + last_updated = models.DateTimeField(auto_now=True) + enable_comments = models.BooleanField(default=False) + PUB_STATUS = ( + (0, 'Draft'), + (1, 'Published'), + ) + status = models.IntegerField(choices=PUB_STATUS, default=0) + featured_image = models.ForeignKey(LuxImage, on_delete=models.CASCADE, null=True, blank=True) + TEMPLATES = ( + (0, 'single'), + ) + POST_TYPE = ( + (0, 'guide'), + (1, 'review'), + (2, 'essay'), + ) + post_type = models.IntegerField(choices=POST_TYPE, default=0) + template_name = models.IntegerField(choices=TEMPLATES, default=0) + has_video = models.BooleanField(blank=True, default=False) + disclaimer = models.BooleanField(blank=True, default=True) + books = models.ManyToManyField(Book, blank=True) + field_notes = models.ManyToManyField(FieldNote, blank=True) + related = models.ManyToManyField(RelatedPost, blank=True) + tags = TaggableManager(through=TaggedItems, blank=True, help_text='Topics Covered') + category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True, blank=True) + point = models.PointField(null=True, blank=True) + location = models.ForeignKey(Location, on_delete=models.CASCADE, null=True, blank=True) + originally_published_by = models.CharField(max_length=400, null=True, blank=True) + originally_published_by_url = models.CharField(max_length=400, null=True, blank=True) + field_notes = models.ManyToManyField(FieldNote, blank=True) + books = models.ManyToManyField(Book, blank=True) + jrnl = models.ManyToManyField(Entry, blank=True) + + class Meta: + ordering = ('-pub_date',) + get_latest_by = 'pub_date' + + def __str__(self): + return self.title + + def get_absolute_url(self): + if self.post_type == 0: + return reverse('guides:detail', kwargs={"slug": self.slug}) + if self.post_type == 1: + return reverse('reviews:detail', kwargs={"slug": self.slug}) + if self.post_type == 2: + return reverse('essays:detail', kwargs={"slug": self.slug}) + + def comment_period_open(self): + return self.enable_comments and datetime.datetime.today() - datetime.timedelta(30) <= self.pub_date + + def get_featured_image_thumb(self): + return self.featured_image.get_image_by_size("tn") + + def get_content_type(self): + return ContentType.objects.get(app_label="posts", model="post") + + @property + def get_previous_published(self): + return self.get_previous_by_pub_date(status__exact=1) + + @property + def get_previous_admin_url(self): + n = self.get_previous_by_pub_date() + return reverse('admin:%s_%s_change' %(self._meta.app_label, self._meta.model_name), args=[n.id] ) + + @property + def get_next_published(self): + return self.get_next_by_pub_date(status__exact=1) + + @property + def get_next_admin_url(self): + model = apps.get_model(app_label=self._meta.app_label, model_name=self._meta.model_name) + try: + return reverse('admin:%s_%s_change' %(self._meta.app_label, self._meta.model_name), args=[self.get_next_by_pub_date().pk] ) + except model.DoesNotExist: + return '' + + @property + def longitude(self): + '''Get the site's longitude.''' + return self.point.x + + @property + def latitude(self): + '''Get the site's latitude.''' + return self.point.y + + def save(self, *args, **kwargs): + created = self.pk is None + if not created: + md = render_images(self.body_markdown) + self.body_html = markdown_to_html(md) + self.epilogue_html = markdown_to_html(self.epilogue_markdown) + self.prologue_html = markdown_to_html(self.prologue_markdown) + self.has_video = parse_video(self.body_html) + if self.point: + try: + self.location = Location.objects.filter(geometry__contains=self.point).get() + except Location.DoesNotExist: + raise forms.ValidationError("There is no location associated with that point, add it: %sadmin/locations/location/add/" % (settings.BASE_URL)) + if created and not self.featured_image: + self.featured_image = LuxImage.objects.latest() + old = type(self).objects.get(pk=self.pk) if self.pk else None + if old and old.featured_image != self.featured_image: # Field has changed + s = LuxImageSize.objects.get(name="featured_jrnl") + ss = LuxImageSize.objects.get(name="picwide-med") + self.featured_image.sizes.add(s) + self.featured_image.sizes.add(ss) + self.featured_image.save() + super(Post, self).save(*args, **kwargs) + + +class PostModerator(CommentModerator): + ''' + Moderate everything except people with multiple approvals + ''' + email_notification = True + + def moderate(self, comment, content_object, request): + previous_approvals = Comment.objects.filter(user_email=comment.email, is_public=True) + for approval in previous_approvals: + if approval.submit_date <= datetime.datetime.today() - datetime.timedelta(21): + approve = True + if previous_approvals.count() > 2 and approve: + return False + # do entry build right here so it goes to live site + return True +moderator.register(Post, PostModerator) + + +@receiver(comment_was_posted, sender=Comment) +def cache_gravatar(sender, comment, **kwargs): + gravatar_exists = has_gravatar(comment.email) + grav_dir = settings.IMAGES_ROOT + '/gravcache/' + if gravatar_exists: + url = get_gravatar_url(comment.email, size=60) + if not os.path.isdir(grav_dir): + os.makedirs(grav_dir) + local_grav = '%s/%s.jpg' % (grav_dir, calculate_gravatar_hash(comment.email)) + urllib.request.urlretrieve(url, local_grav) + + +@receiver(post_save, sender=Post) +def post_save_events(sender, update_fields, created, instance, **kwargs): + related, created = RelatedPost.objects.get_or_create(model_name=instance.get_content_type(), entry_id = instance.id) + related.title = instance.title + related.slug = instance.slug + post_save.disconnect(post_save_events, sender=Post) + instance.save() + post_save.connect(post_save_events, sender=Post) diff --git a/app/posts/review_urls.py b/app/posts/review_urls.py new file mode 100644 index 0000000..f6a3908 --- /dev/null +++ b/app/posts/review_urls.py @@ -0,0 +1,29 @@ +from django.urls import path, re_path + +from . import views + +app_name = "reviews" + +urlpatterns = [ + path( + r'<str:slug>', + views.PostDetailView.as_view(), + name="review-detail" + ), + path( + r'<str:slug>.txt', + views.PostDetailViewTXT.as_view(), + name="review-detail-txt" + ), + path( + r'<int:page>/', + views.GuidesListView.as_view(), + name="review-list" + ), + path( + r'', + views.GuidesListView.as_view(), + {'page':1}, + name="review-list" + ), +] diff --git a/app/posts/templates/horizontal_select.html b/app/posts/templates/horizontal_select.html new file mode 100644 index 0000000..61dcfd8 --- /dev/null +++ b/app/posts/templates/horizontal_select.html @@ -0,0 +1,17 @@ +{% with id=widget.attrs.id %} + <ul{% if id %} id="{{ id }}"{% endif %}{% if widget.attrs.class %} class="{{ widget.attrs.class }}"{% endif %}> + {% for group, options, index in widget.optgroups %} + {% if group %} + <li>{{ group }} + <ul{% if id %} id="{{ id }}_{{ index }}"{% endif %}> + {% endif %} + {% for option in options %} + <li data-imageid="{{option.value}}" data-loopcounter="{{forloop.parentloop.counter}}">{% include option.template_name with widget=option %}</li> + {% endfor %} + {% if group %} + </ul> + </li> + {% endif %} + {% endfor %} + </ul> +{% endwith %} diff --git a/app/posts/templates/posts/entry_detail.txt b/app/posts/templates/posts/entry_detail.txt new file mode 100644 index 0000000..547ce79 --- /dev/null +++ b/app/posts/templates/posts/entry_detail.txt @@ -0,0 +1,8 @@ +{{object.title|safe}} +{% for letter in object.title %}={%endfor%} + + by Scott Gilbertson + <{{SITE_URL}}{{object.get_absolute_url}}> + {{object.pub_date|date:"l, d F Y"}} + +{{object.body_markdown|safe}} diff --git a/app/posts/templates/posts/essay_detail.html b/app/posts/templates/posts/essay_detail.html new file mode 100644 index 0000000..1ef602a --- /dev/null +++ b/app/posts/templates/posts/essay_detail.html @@ -0,0 +1,176 @@ +{% extends 'base.html' %} +{% load typogrify_tags %} +{% load comments %} +{%block htmlclass%}class="detail single"{%endblock%} +{% block pagetitle %}{{object.title|title|smartypants|safe}} - by Scott Gilbertson{% endblock %} + +{% block metadescription %}{% autoescape on %}{{object.meta_description|striptags|safe}}{% endautoescape %}{% endblock %} +{%block extrahead%} +{% if object.has_code %} + <link rel="stylesheet" href="/media/src/solarized.css" type="text/css" media="screen"/> +{%endif %} + <link rel="canonical" href="https://luxagraf.net{{object.get_absolute_url}}" /> + <meta property="og:type" content="article" /> + <meta property="og:title" content="{{object.title|safe}}" /> + <meta property="og:url" content="https://luxagraf.net{{object.get_absolute_url}}" /> + <meta property="og:description" content="{% if object.meta_description %}{{object.meta_description}}{%else%}{{object.sub_title}}{%endif%}" /> + <meta property="article:published_time" content="{{object.pub_date|date:'c'}}" /> + <meta property="article:author" content="Scott Gilbertson" /> + <meta property="og:site_name" content="Luxagraf" /> + <meta property="og:image" content="{{self.get_featured_image}}" /> + <meta property="og:locale" content="en_US" /> + <meta name="twitter:card" content="summary_large_image"/> + <meta name="twitter:description" content="{% if object.meta_description %}{{object.meta_description}}{%else%}{{object.sub_title}}{%endif%}"/> + <meta name="twitter:title" content="{{object.title|safe}}"/> + <meta name="twitter:site" content="@luxagraf"/> + <meta name="twitter:domain" content="luxagraf"/>{% if object.featured_image %} + <meta name="twitter:image:src" content="{{object.featured_image.get_image_url}}"/>{%endif%} + <meta name="twitter:creator" content="@luxagraf"/> +{%endblock%} + +{%block bodyid %}{% if object.get_post_type_display == 'tools' %}class="src"{% endif %}{%endblock%} + +{% block primary %} + <main> + <article class="h-entry hentry {% with object.get_template_name_display as t %}{%if t == "double" or t == "double-dark" %} post--article--double{%endif%}{%endwith%}" itemscope itemType="http://schema.org/Article"> + <header id="header" class="post-header {% with object.get_template_name_display as t %}{%if t == "double" or t == "double-dark" %}post--header--double{%endif%}{%endwith%}"> + <h1 class="p-name entry-title post-title" itemprop="headline">{%if object.template_name == 1 or object.template_name == 3 %}{{object.title|smartypants|safe}}{%else%}{{object.title|smartypants|safe}}{%endif%}</h1> + <h2 class="post-subtitle">{{object.sub_title|smartypants|safe}}</h2> + <div class="post-linewrapper"> + {% if object.originally_published_by %}<h4 class="post-source">Originally Published By: <a href="{{object.originally_published_by_url}}" title="View {{object.title}} on {{object.originally_published_by}}">{{object.originally_published_by}}</a></h4>{%endif%} + {% if object.location %}<div class="p-location h-adr adr post-location" itemprop="contentLocation" itemscope itemtype="http://schema.org/Place"> + <h3 class="h-adr" itemprop="address" itemscope itemtype="http://schema.org/PostalAddress">{% if object.location.country_name == "United States" %}<span class="p-locality locality" itemprop="addressLocality">{{object.location.name|smartypants|safe}}</span>, <a class="p-region region" href="/jrnl/united-states/" title="travel writing from the United States">{{object.location.state_name|safe}}</a>, <span class="p-country-name" itemprop="addressCountry">U.S.</span>{%else%}<span class="p-region" itemprop="addressRegion">{{object.location.name|smartypants|safe}}</span>, <a class="p-country-name country-name" href="/jrnl/{{object.location.country_slug}}/" title="travel writing from {{object.location.country_name}}"><span itemprop="addressCountry">{{object.location.country_name|safe}}</span></a>{%endif%}</h3> + – <a href="" onclick="showMap({{object.latitude}}, {{object.longitude}}, { type:'point', lat:'{{object.latitude}}', lon:'{{object.longitude}}'}); return false;" title="see a map">Map</a> + </div>{%endif%} + <time class="dt-published published dt-updated post-date" datetime="{{object.pub_date|date:'c'}}" itemprop="datePublished">{{object.pub_date|date:"F"}} <span>{{object.pub_date|date:"j, Y"}}</span></time> + <span class="hide" itemprop="author" itemscope itemtype="http://schema.org/Person">by <a class="p-author h-card" href="/about"><span itemprop="name">Scott Gilbertson</span></a></span> + </div> + </header> + <div id="article" class="e-content entry-content post--body post--body--{% with object.template_name as t %}{%if t == 0 or t == 2 %}single{%endif%}{%if t == 1 or t == 3 %}double{%endif%}{%endwith%} post-essay" itemprop="articleBody"> + {% if object.preamble %}<div class="afterward"> + {{object.preamble_html|smartypants|safe}} + </div>{%endif%} + {{object.body_html|safe|smartypants}} + </div> + {% if object.afterword_html %}<div class="afterward"> + <h4>Afterward</h4> + {{object.afterword_html|smartypants|safe}} + </div>{%endif%} + {%if wildlife or object.field_notes.all or object.books.all %}<div class="entry-footer">{%if wildlife %} + <aside id="wildlife"> + <h3>Fauna and Flora</h3> + {% regroup wildlife by ap.apclass.get_kind_display as wildlife_list %} + <ul> + {% for object_list in wildlife_list %} + <li class="grouper">{{object_list.grouper}}<ul> + {% for object in object_list.list %} + <li>{%if object.ap.body_markdown%}<a href="{% url 'sightings:detail' object.ap.slug %}">{{object}}</a>{%else%}{{object}}{%endif%} </li> + {% endfor %}</ul> + {% endfor %}</ul> + </aside> + {% endif %}{%if object.field_notes.all %} + <aside {% if wildlife %}class="margin-left-none" {%endif%}id="field_notes"> + <h3>Field Notes</h3> + <ul>{% for obj in object.field_notes.all %} + <li><a href="{% url 'fieldnotes:detail' year=obj.pub_date.year month=obj.pub_date|date:"m" slug=obj.slug %}">{{obj}}</a></li> + {% endfor %}</ul> + </aside>{% endif %} + {%if object.books.all %} + <aside id="recommended-reading" {%if object.field_notes.all and wildlife %}class="rr-clear{%endif%}" > + <h3>Recommended Reading</h3> + <ul>{% for obj in object.books.all %} + <li><a href="{% url 'books:detail' slug=obj.slug %}"><img src="{{obj.get_small_image_url}}" /></a></li> + {% endfor %}</ul> + </aside>{% endif %} + </div>{%endif%} + </article> + + {% comment %} <div class="mailing-list--wrapper"> + <h5>If you enjoyed this, you should join the mailing list…</h5> + {% include 'mailing_list.html' %} + </div> {% endcomment %} + </main> + {% if object.enable_comments %} +{% get_comment_count for object as comment_count %} +{%if comment_count > 0 %} +<p class="comments--header">{{comment_count}} Comment{{ comment_count|pluralize }}</p> +{% render_comment_list for object %} +{%endif%} +{% render_comment_form for object %} +{% else %} +<p class="comments--header" style="text-align: center">Sorry, comments have been disabled for this post.</p> +{%endif%} +{% endblock %} +{% block js %} +<script type="text/javascript"> +document.addEventListener("DOMContentLoaded", function(event) { + var leaflet = document.createElement('script'); + leaflet.src = "/media/js/leaflet-master/leaflet-mod.js"; + document.body.appendChild(leaflet); + var lightbox = document.createElement('script'); + lightbox.src = "/media/js/lightbox.js"; + document.body.appendChild(lightbox); + leaflet.onload = function(){ + var detail = document.createElement('script'); + detail.src = "/media/js/detail.min.js"; + document.body.appendChild(detail); + {% with object.get_template_name_display as t %}{%if t == "single" or t == "single-dark" %} + detail.onload = function(){ + createMap(); + var open = false; + } + {%endif%}{%endwith%} + } + + lightbox.onload = function() { + var opts= { + //nextOnClick: false, + captions: true, + onload: function(){ + var im = document.getElementById("jslghtbx-contentwrapper"); + var link = im.appendChild(document.createElement('a')) + link.href = im.firstChild.src; + link.innerHTML= "open "; + link.target = "_blank"; + link.setAttribute('class', 'p-link'); + im.appendChild(link); + } + }; + var lightbox = new Lightbox(); + lightbox.load(opts); + } + {% if object.enable_comments %} +{% get_comment_count for object as comment_count %} +{%if comment_count > 0 %} + //delay loading of gravatar images using noscript data-hash attribute + dataattr = document.getElementsByClassName("datahashloader"); + for(var i=0; i<dataattr.length; i++) { + var c = dataattr[i].parentNode; + var img = document.createElement("img"); + img.src = 'https://images.luxagraf.net/gravcache/' + dataattr[i].getAttribute('data-hash') + '.jpg'; + img.className += "gravatar"; + c.insertBefore(img, c.childNodes[3]); + } +{%endif%} +{%endif%} +{% if object.has_video %} +var tester = document.getElementsByClassName("vidauto"); +var wrapper = document.getElementById('wrapper'); +var dist = 100; + +window.onscroll = function() { + for (var i=0; i<tester.length; i++) { + checkVisible(tester[i]) ? tester[i].play() : tester[i].pause(); + } +}; + +function checkVisible(elm) { + var rect = elm.getBoundingClientRect(); + var viewHeight = Math.max(document.documentElement.clientHeight, window.innerHeight); + return !(rect.bottom < 0 || rect.top - viewHeight >= 0); +} +{%endif%} + +}); +</script> +{%endblock%} diff --git a/app/posts/templates/posts/essay_list.html b/app/posts/templates/posts/essay_list.html new file mode 100644 index 0000000..271f83f --- /dev/null +++ b/app/posts/templates/posts/essay_list.html @@ -0,0 +1,28 @@ +{% extends 'base.html' %} +{% load typogrify_tags %} + +{% block pagetitle %}Collected Essays of Scott Gilbertson {% endblock %} +{% block metadescription %}Collected writing: essays, articles and stories on travel, photography, tools, walking, the natural world and other ephemera.{% endblock %} + +{% block primary %}<ul class="bl" id="breadcrumbs" itemscope itemtype="http://data-vocabulary.org/Breadcrumb"> + <li><a href="/" title="luxagraf homepage" itemprop="url"><span itemprop="title">Home</span></a> → </li> + <li>Essays</li> + </ul> + <main role="main" id="essay-archive" class="essay-archive archive-list"> + <div class="essay-intro"> + <h2>My various articles and essays collected in one spot.</h2> + <p>Topics include travel, writing, photography, free software, culture, and once, Del Taco.</p> + <p>Many essays below were previously published in: <em><a href="https://www.wired.com/author/scott-gilbertson/">WIRED</a></em>, <em><a href="https://www.budgettravel.com/article/0902_HTTN_SocialNetwork_5488">Budget Travel</a></em>, <em><a href="https://arstechnica.com/">Ars Technica</a></em>, <em><a href="https://web.archive.org/web/20100904114555/http://one.longshotmag.com/article/going-for-seconds">Longshot Magazine</a>,</em> <em><a href="https://web.archive.org/web/20150506051746/http://1888.center/scott-gilbertson/">The Cost of Paper</a></em> and elsewhere.</a></p> + </div> + <h1 class="topic-hed">Essays</h1> + <ul>{% for object in object_list %} + <li class="h-entry hentry" itemscope itemType="http://schema.org/Article"> + <span class="date dt-published">{{object.pub_date|date:"F Y"}}</span> + <a href="{{object.get_absolute_url}}"> + <h2>{{object.title|safe|smartypants|widont}}</h2> + <p class="p-summary">{% if object.subtitle %}{{object.subtitle|safe|smartypants}}{%else%}{{object.meta_description}}{%endif%}</p> + </a> + </li> + {%endfor%}</ul> + </main> +{%endblock%} diff --git a/app/posts/templates/posts/post_detail.html b/app/posts/templates/posts/post_detail.html new file mode 100644 index 0000000..1ef602a --- /dev/null +++ b/app/posts/templates/posts/post_detail.html @@ -0,0 +1,176 @@ +{% extends 'base.html' %} +{% load typogrify_tags %} +{% load comments %} +{%block htmlclass%}class="detail single"{%endblock%} +{% block pagetitle %}{{object.title|title|smartypants|safe}} - by Scott Gilbertson{% endblock %} + +{% block metadescription %}{% autoescape on %}{{object.meta_description|striptags|safe}}{% endautoescape %}{% endblock %} +{%block extrahead%} +{% if object.has_code %} + <link rel="stylesheet" href="/media/src/solarized.css" type="text/css" media="screen"/> +{%endif %} + <link rel="canonical" href="https://luxagraf.net{{object.get_absolute_url}}" /> + <meta property="og:type" content="article" /> + <meta property="og:title" content="{{object.title|safe}}" /> + <meta property="og:url" content="https://luxagraf.net{{object.get_absolute_url}}" /> + <meta property="og:description" content="{% if object.meta_description %}{{object.meta_description}}{%else%}{{object.sub_title}}{%endif%}" /> + <meta property="article:published_time" content="{{object.pub_date|date:'c'}}" /> + <meta property="article:author" content="Scott Gilbertson" /> + <meta property="og:site_name" content="Luxagraf" /> + <meta property="og:image" content="{{self.get_featured_image}}" /> + <meta property="og:locale" content="en_US" /> + <meta name="twitter:card" content="summary_large_image"/> + <meta name="twitter:description" content="{% if object.meta_description %}{{object.meta_description}}{%else%}{{object.sub_title}}{%endif%}"/> + <meta name="twitter:title" content="{{object.title|safe}}"/> + <meta name="twitter:site" content="@luxagraf"/> + <meta name="twitter:domain" content="luxagraf"/>{% if object.featured_image %} + <meta name="twitter:image:src" content="{{object.featured_image.get_image_url}}"/>{%endif%} + <meta name="twitter:creator" content="@luxagraf"/> +{%endblock%} + +{%block bodyid %}{% if object.get_post_type_display == 'tools' %}class="src"{% endif %}{%endblock%} + +{% block primary %} + <main> + <article class="h-entry hentry {% with object.get_template_name_display as t %}{%if t == "double" or t == "double-dark" %} post--article--double{%endif%}{%endwith%}" itemscope itemType="http://schema.org/Article"> + <header id="header" class="post-header {% with object.get_template_name_display as t %}{%if t == "double" or t == "double-dark" %}post--header--double{%endif%}{%endwith%}"> + <h1 class="p-name entry-title post-title" itemprop="headline">{%if object.template_name == 1 or object.template_name == 3 %}{{object.title|smartypants|safe}}{%else%}{{object.title|smartypants|safe}}{%endif%}</h1> + <h2 class="post-subtitle">{{object.sub_title|smartypants|safe}}</h2> + <div class="post-linewrapper"> + {% if object.originally_published_by %}<h4 class="post-source">Originally Published By: <a href="{{object.originally_published_by_url}}" title="View {{object.title}} on {{object.originally_published_by}}">{{object.originally_published_by}}</a></h4>{%endif%} + {% if object.location %}<div class="p-location h-adr adr post-location" itemprop="contentLocation" itemscope itemtype="http://schema.org/Place"> + <h3 class="h-adr" itemprop="address" itemscope itemtype="http://schema.org/PostalAddress">{% if object.location.country_name == "United States" %}<span class="p-locality locality" itemprop="addressLocality">{{object.location.name|smartypants|safe}}</span>, <a class="p-region region" href="/jrnl/united-states/" title="travel writing from the United States">{{object.location.state_name|safe}}</a>, <span class="p-country-name" itemprop="addressCountry">U.S.</span>{%else%}<span class="p-region" itemprop="addressRegion">{{object.location.name|smartypants|safe}}</span>, <a class="p-country-name country-name" href="/jrnl/{{object.location.country_slug}}/" title="travel writing from {{object.location.country_name}}"><span itemprop="addressCountry">{{object.location.country_name|safe}}</span></a>{%endif%}</h3> + – <a href="" onclick="showMap({{object.latitude}}, {{object.longitude}}, { type:'point', lat:'{{object.latitude}}', lon:'{{object.longitude}}'}); return false;" title="see a map">Map</a> + </div>{%endif%} + <time class="dt-published published dt-updated post-date" datetime="{{object.pub_date|date:'c'}}" itemprop="datePublished">{{object.pub_date|date:"F"}} <span>{{object.pub_date|date:"j, Y"}}</span></time> + <span class="hide" itemprop="author" itemscope itemtype="http://schema.org/Person">by <a class="p-author h-card" href="/about"><span itemprop="name">Scott Gilbertson</span></a></span> + </div> + </header> + <div id="article" class="e-content entry-content post--body post--body--{% with object.template_name as t %}{%if t == 0 or t == 2 %}single{%endif%}{%if t == 1 or t == 3 %}double{%endif%}{%endwith%} post-essay" itemprop="articleBody"> + {% if object.preamble %}<div class="afterward"> + {{object.preamble_html|smartypants|safe}} + </div>{%endif%} + {{object.body_html|safe|smartypants}} + </div> + {% if object.afterword_html %}<div class="afterward"> + <h4>Afterward</h4> + {{object.afterword_html|smartypants|safe}} + </div>{%endif%} + {%if wildlife or object.field_notes.all or object.books.all %}<div class="entry-footer">{%if wildlife %} + <aside id="wildlife"> + <h3>Fauna and Flora</h3> + {% regroup wildlife by ap.apclass.get_kind_display as wildlife_list %} + <ul> + {% for object_list in wildlife_list %} + <li class="grouper">{{object_list.grouper}}<ul> + {% for object in object_list.list %} + <li>{%if object.ap.body_markdown%}<a href="{% url 'sightings:detail' object.ap.slug %}">{{object}}</a>{%else%}{{object}}{%endif%} </li> + {% endfor %}</ul> + {% endfor %}</ul> + </aside> + {% endif %}{%if object.field_notes.all %} + <aside {% if wildlife %}class="margin-left-none" {%endif%}id="field_notes"> + <h3>Field Notes</h3> + <ul>{% for obj in object.field_notes.all %} + <li><a href="{% url 'fieldnotes:detail' year=obj.pub_date.year month=obj.pub_date|date:"m" slug=obj.slug %}">{{obj}}</a></li> + {% endfor %}</ul> + </aside>{% endif %} + {%if object.books.all %} + <aside id="recommended-reading" {%if object.field_notes.all and wildlife %}class="rr-clear{%endif%}" > + <h3>Recommended Reading</h3> + <ul>{% for obj in object.books.all %} + <li><a href="{% url 'books:detail' slug=obj.slug %}"><img src="{{obj.get_small_image_url}}" /></a></li> + {% endfor %}</ul> + </aside>{% endif %} + </div>{%endif%} + </article> + + {% comment %} <div class="mailing-list--wrapper"> + <h5>If you enjoyed this, you should join the mailing list…</h5> + {% include 'mailing_list.html' %} + </div> {% endcomment %} + </main> + {% if object.enable_comments %} +{% get_comment_count for object as comment_count %} +{%if comment_count > 0 %} +<p class="comments--header">{{comment_count}} Comment{{ comment_count|pluralize }}</p> +{% render_comment_list for object %} +{%endif%} +{% render_comment_form for object %} +{% else %} +<p class="comments--header" style="text-align: center">Sorry, comments have been disabled for this post.</p> +{%endif%} +{% endblock %} +{% block js %} +<script type="text/javascript"> +document.addEventListener("DOMContentLoaded", function(event) { + var leaflet = document.createElement('script'); + leaflet.src = "/media/js/leaflet-master/leaflet-mod.js"; + document.body.appendChild(leaflet); + var lightbox = document.createElement('script'); + lightbox.src = "/media/js/lightbox.js"; + document.body.appendChild(lightbox); + leaflet.onload = function(){ + var detail = document.createElement('script'); + detail.src = "/media/js/detail.min.js"; + document.body.appendChild(detail); + {% with object.get_template_name_display as t %}{%if t == "single" or t == "single-dark" %} + detail.onload = function(){ + createMap(); + var open = false; + } + {%endif%}{%endwith%} + } + + lightbox.onload = function() { + var opts= { + //nextOnClick: false, + captions: true, + onload: function(){ + var im = document.getElementById("jslghtbx-contentwrapper"); + var link = im.appendChild(document.createElement('a')) + link.href = im.firstChild.src; + link.innerHTML= "open "; + link.target = "_blank"; + link.setAttribute('class', 'p-link'); + im.appendChild(link); + } + }; + var lightbox = new Lightbox(); + lightbox.load(opts); + } + {% if object.enable_comments %} +{% get_comment_count for object as comment_count %} +{%if comment_count > 0 %} + //delay loading of gravatar images using noscript data-hash attribute + dataattr = document.getElementsByClassName("datahashloader"); + for(var i=0; i<dataattr.length; i++) { + var c = dataattr[i].parentNode; + var img = document.createElement("img"); + img.src = 'https://images.luxagraf.net/gravcache/' + dataattr[i].getAttribute('data-hash') + '.jpg'; + img.className += "gravatar"; + c.insertBefore(img, c.childNodes[3]); + } +{%endif%} +{%endif%} +{% if object.has_video %} +var tester = document.getElementsByClassName("vidauto"); +var wrapper = document.getElementById('wrapper'); +var dist = 100; + +window.onscroll = function() { + for (var i=0; i<tester.length; i++) { + checkVisible(tester[i]) ? tester[i].play() : tester[i].pause(); + } +}; + +function checkVisible(elm) { + var rect = elm.getBoundingClientRect(); + var viewHeight = Math.max(document.documentElement.clientHeight, window.innerHeight); + return !(rect.bottom < 0 || rect.top - viewHeight >= 0); +} +{%endif%} + +}); +</script> +{%endblock%} diff --git a/app/posts/templates/posts/post_detail.txt b/app/posts/templates/posts/post_detail.txt new file mode 100644 index 0000000..547ce79 --- /dev/null +++ b/app/posts/templates/posts/post_detail.txt @@ -0,0 +1,8 @@ +{{object.title|safe}} +{% for letter in object.title %}={%endfor%} + + by Scott Gilbertson + <{{SITE_URL}}{{object.get_absolute_url}}> + {{object.pub_date|date:"l, d F Y"}} + +{{object.body_markdown|safe}} diff --git a/app/posts/templates/posts/post_list.html b/app/posts/templates/posts/post_list.html new file mode 100644 index 0000000..a264a11 --- /dev/null +++ b/app/posts/templates/posts/post_list.html @@ -0,0 +1,40 @@ +{% extends 'base.html' %} +{% load typogrify_tags %} +{% load html5_datetime %} +{% load pagination_tags %} +{% block pagetitle %}Guides for the Perplexed{% endblock %} +{% block metadescription %}Guides for fellow travelers: tools, tips, and tricks to make life on the road easier.{% endblock %} + +{% block primary %}<ul class="bl" id="breadcrumbs" itemscope itemtype="http://data-vocabulary.org/Breadcrumb"> + <li><a href="/" title="luxagraf homepage" itemprop="url"><span itemprop="title">Home</span></a> → </li> + <li>Essays</li> + </ul> + <main role="main" id="essay-archive" class="essay-archive archive-list"> + <div class="essay-intro"> + <h2>Guides for fellow travelers</h2> + <p>The less stuff you travel with the better off you will be, up to a point. But where is that point? What's enough? What's too much? That point is what I'm trying to discover here. </p> + <p>What do you really need? What's worth having? What's not?</p> + <p>Topics include {% for topic in topic_list %}{{topic}}, {% endfor %}travel, cooking, photography, writing, simplicity, and once, coffee.</p> + </div> + <h1 class="topic-hed">Guides</h1> + {% autopaginate object_list 30 %} + <ul class="fancy-archive-list">{% for object in object_list %} + <li class="h-entry hentry" itemscope itemType="http://schema.org/Article"> + <a href="{{object.get_absolute_url}}" class="u-url"> + <div class="circle-img-wrapper"><img src="{{object.featured_image.get_thumbnail_url}}" alt="{{object.featured_image.alt}}" class="u-photo" /></div> + <span class="date dt-published">{{object.pub_date|date:"F d, Y"}}</span> + <a href="{{object.get_absolute_url}}"> + <h2>{{object.title|safe|smartypants|widont}}</h2> + {% if object.subtitle %}<h3 class="p-summary">{{object.subtitle|safe|smartypants|widont}}</h3>{%endif%} + </a> + {% if object.location %}<h4 class="p-location h-adr post-location" itemprop="geo" itemscope itemtype="http://data-vocabulary.org/Geo"> + <span class="p-locality">{{object.location.name|smartypants|safe}}</span>, + <span class="p-region">{{object.location.state_name}}</span>, + <span class="p-country-name">{{object.location.country_name}}</span> + <data class="p-latitude" value="{{object.latitude}}"></data> + <data class="p-longitude" value="{{object.longitude}}"></data> + </h4>{% endif %} + </li> + {%endfor%}</ul> + </main> +{%endblock%} diff --git a/app/posts/urls.py b/app/posts/urls.py new file mode 100644 index 0000000..322e5ad --- /dev/null +++ b/app/posts/urls.py @@ -0,0 +1,24 @@ +from django.urls import path, re_path +from django.views.generic.base import RedirectView + +from . import views + +app_name = "posts" + +urlpatterns = [ + path( + r'<str:slug>.txt', + views.EntryDetailViewTXT.as_view(), + name="detail-txt" + ), + path( + r'<str:slug>', + views.EntryDetailView.as_view(), + name="detail" + ), + re_path( + r'<int:page>/', + views.EntryList.as_view(), + name="list" + ), +] diff --git a/app/posts/views.py b/app/posts/views.py new file mode 100644 index 0000000..0324d16 --- /dev/null +++ b/app/posts/views.py @@ -0,0 +1,75 @@ +from django.views.generic import ListView +from django.views.generic.detail import DetailView +from django.contrib.syndication.views import Feed +from django.apps import apps +from django.conf import settings + +from utils.views import PaginatedListView + +from .models import Post +from taxonomy.models import Category + + +class PostList(PaginatedListView): + """ + Return a list of Entries in reverse chronological order + """ + model = Post + + def get_queryset(self): + queryset = super(PostList, self).get_queryset() + return queryset.filter(status__exact=1).order_by('-pub_date').prefetch_related('location').prefetch_related('featured_image') + + +class GuidesListView(PostList): + + def get_queryset(self): + queryset = super(GuidesListView, self).get_queryset() + return queryset.filter(post_type__in=[0,1]).filter(status__exact=1).order_by('-pub_date').prefetch_related('location').prefetch_related('featured_image') + + +class EssayListView(PostList): + template_name = "posts/essay_list.html" + + def get_queryset(self): + queryset = super(EssayListView, self).get_queryset() + return queryset.filter(post_type__in=[2,]).filter(status__exact=1).order_by('-pub_date').prefetch_related('location').prefetch_related('featured_image') + + +class PostDetailView(DetailView): + model = Post + slug_field = "slug" + + def get_queryset(self): + queryset = super(PostDetailView, self).get_queryset() + return queryset.select_related('location').prefetch_related('field_notes') + + def get_context_data(self, **kwargs): + context = super(PostDetailView, self).get_context_data(**kwargs) + related = [] + for obj in self.object.related.all(): + model = apps.get_model(obj.post_model.app_label, obj.post_model.model) + related.append(model.objects.get(slug=obj.slug)) + context['related'] = related + return context + + +class PostDetailViewTXT(PostDetailView): + template_name = "posts/entry_detail.txt" + + +class PostsRSSFeedView(Feed): + title = "VanLifeReviews.com: " + link = "/" + description = "Latest reviews, stories and guides" + description_template = 'feeds/blog_description.html' + + def items(self): + return Post.objects.filter(status__exact=1).order_by('-pub_date')[:10] + + def item_pubdate(self, item): + """ + Takes an item, as returned by items(), and returns the item's + pubdate. + """ + return item.pub_date |