summaryrefslogtreecommitdiff
path: root/app/blog
diff options
context:
space:
mode:
authorluxagraf <sng@luxagraf.net>2014-05-23 11:28:10 -0400
committerluxagraf <sng@luxagraf.net>2014-05-23 11:28:10 -0400
commit518b2d618bc10f93cfa44a83715593b8358eb9ce (patch)
treea07993c3ae31bed42f32c0e00788989568790716 /app/blog
parent4bae11bb25a8e3c43118891d17fd8e981ecf8dc6 (diff)
minor refactor to adoipt pep8 and pyflakes coding styles and clean up
some cruft that's been hangin round for years
Diffstat (limited to 'app/blog')
-rw-r--r--app/blog/admin.py59
-rw-r--r--app/blog/fields.py1
-rw-r--r--app/blog/models.py98
-rwxr-xr-xapp/blog/parse.py26
-rw-r--r--app/blog/urls.py2
-rw-r--r--app/blog/views.py52
-rw-r--r--app/blog/widgets.py8
7 files changed, 131 insertions, 115 deletions
diff --git a/app/blog/admin.py b/app/blog/admin.py
index d756b18..0d7a2b7 100644
--- a/app/blog/admin.py
+++ b/app/blog/admin.py
@@ -3,11 +3,9 @@ from django import forms
from blog.models import Entry, PostImage, EntryAside
from blog.widgets import AdminImageWidget
from django.contrib.gis.admin import OSMGeoAdmin
-from django.conf import settings
from .models import *
-
class EntryAsideInline(admin.TabularInline):
model = EntryAside
extra = 1
@@ -16,32 +14,56 @@ class EntryAsideInline(admin.TabularInline):
class EntryAsideAdmin(admin.ModelAdmin):
pass
+
class BlogEntryForm(forms.ModelForm):
class Meta:
model = Entry
widgets = {
- 'body_markdown': forms.Textarea(attrs={'rows':50, 'cols':100}),
+ 'body_markdown': forms.Textarea(attrs={'rows': 50, 'cols': 100}),
}
-
+
class EntryAdmin(OSMGeoAdmin):
form = BlogEntryForm
- inlines = [EntryAsideInline,]
+ inlines = [EntryAsideInline]
+
def formfield_for_dbfield(self, db_field, **kwargs):
- if db_field.name == 'thumbnail' or db_field.name == 'image' :
+ if db_field.name == 'thumbnail' or db_field.name == 'image':
field = forms.FileField(widget=AdminImageWidget)
else:
- field = super(EntryAdmin,self).formfield_for_dbfield(db_field,**kwargs)
+ field = super(EntryAdmin, self).formfield_for_dbfield(db_field, **kwargs)
return field
- list_display = ('title', 'pub_date','template_name', 'status','region','location','photo_gallery')
+
+ list_display = ('title', 'pub_date', 'template_name', 'status', 'region', 'location', 'photo_gallery')
search_fields = ['title', 'body_markdown']
- prepopulated_fields = {"slug" : ('title',)}
- list_filter = ('pub_date', 'enable_comments', 'status','location__state__country__lux_region',)
+ prepopulated_fields = {"slug": ('title',)}
+ list_filter = ('pub_date', 'enable_comments', 'status', 'location__state__country__lux_region')
fieldsets = (
- ('Entry', {'fields': ('title','body_markdown', ('pub_date', 'status'), 'slug','point'), 'classes': ('show','extrapretty','wide')}),
- ('Formatting data', {'fields': ('dek','meta_description', ('image','thumbnail',),'template_name'), 'classes': ('grp-collapse grp-closed',)}),
+ ('Entry', {
+ 'fields': (
+ 'title',
+ 'body_markdown',
+ ('pub_date', 'status'),
+ 'slug',
+ 'point'
+ ),
+ 'classes': (
+ 'show',
+ 'extrapretty',
+ 'wide'
+ )
+ }
+ ),
+ ('Formatting data', {
+ 'fields': (
+ 'dek',
+ 'meta_description',
+ ('image', 'thumbnail'),
+ 'template_name'
+ ),
+ }),
)
-
+
class Media:
js = ['/media/admin/custom/model.js']
map_template = 'gis/admin/osm.html'
@@ -49,7 +71,7 @@ class EntryAdmin(OSMGeoAdmin):
# Uncomment and modify as desired
# To learn more about this jargon visit:
# www.openlayers.org
-
+
default_lon = -9314310
default_lat = 3991847
default_zoom = 6
@@ -81,8 +103,9 @@ class EntryAdmin(OSMGeoAdmin):
class PostImageAdmin(admin.ModelAdmin):
- list_display = ('title', 'post_image')
-
-admin.site.register(PostImage, PostImageAdmin)
-admin.site.register(EntryAside, EntryAsideAdmin)
+ list_display = ('title', 'post_image')
+
+
+admin.site.register(PostImage, PostImageAdmin)
+admin.site.register(EntryAside, EntryAsideAdmin)
admin.site.register(Entry, EntryAdmin)
diff --git a/app/blog/fields.py b/app/blog/fields.py
index bab8ad3..6239297 100644
--- a/app/blog/fields.py
+++ b/app/blog/fields.py
@@ -4,4 +4,3 @@ from blog.widgets import AdminImageWidget
class FileUploadForm(forms.ModelForm):
upload = forms.FileField(widget=AdminImageWidget)
-
diff --git a/app/blog/models.py b/app/blog/models.py
index 1876460..e7f10ab 100644
--- a/app/blog/models.py
+++ b/app/blog/models.py
@@ -4,68 +4,70 @@ from django.utils.html import format_html
from django.conf import settings
from django.contrib.syndication.views import Feed
from django.contrib.sitemaps import Sitemap
-from django.template.defaultfilters import truncatewords_html
-from PIL import Image
from django import forms
-
-#http://freewisdom.org/projects/python-markdown/
+# http://freewisdom.org/projects/python-markdown/
import markdown
-
from photos.models import PhotoGallery
-from locations.models import Location,Region
+from locations.models import Location
+
def get_upload_path(self, filename):
- return "images/post-images/%s/%s" %(datetime.datetime.today().strftime("%Y"), filename)
+ return "images/post-images/%s/%s" % (datetime.datetime.today().strftime("%Y"), filename)
+
def get_tn_path(self, filename):
- return "images/post-thumbnail/%s/%s" %(datetime.datetime.today().strftime("%Y"), filename)
+ return "images/post-thumbnail/%s/%s" % (datetime.datetime.today().strftime("%Y"), filename)
+
def image_url_replace(str):
str = str.replace('[[base_url]]', settings.IMAGES_URL)
return str
-PUB_STATUS = (
- (0, 'Draft'),
- (1, 'Published'),
- )
-
-TEMPLATES = (
- (0, 'single'),
- (1, 'double'),
- (2, 'single-dark'),
- (3, 'double-dark'),
- (4, 'bigimg'),
- (5, 'bigimg-dark'),
- )
class PostImage(models.Model):
title = models.CharField(max_length=100)
- image = models.ImageField(upload_to="%s/%s" %(settings.IMAGES_ROOT, datetime.datetime.today().strftime("%Y")))
+ image = models.ImageField(upload_to="%s/%s" % (settings.IMAGES_ROOT, datetime.datetime.today().strftime("%Y")))
def __unicode__(self):
return self.title
-
+
def post_image(self):
- return format_html('<img src="%s%s" alt="%s" class="postpic"/>' % \
- (settings.IMAGES_URL, self.image.url.split('images')[1].split('/',1)[1], self.title))
+ return format_html('<img src="%s%s" alt="%s" class="postpic"/>' % (
+ settings.IMAGES_URL,
+ self.image.url.split('images')[1].split('/', 1)[1],
+ self.title)
+ )
post_image.allow_tags = True
+
class Entry(models.Model):
title = models.CharField(max_length=200)
slug = models.SlugField(unique_for_date='pub_date')
body_html = models.TextField(blank=True)
body_markdown = models.TextField()
- dek = models.TextField(null=True,blank=True)
+ dek = models.TextField(null=True, blank=True)
pub_date = models.DateTimeField('Date published')
enable_comments = models.BooleanField(default=False)
point = models.PointField(null=True, blank=True)
location = models.ForeignKey(Location, null=True, blank=True)
+ PUB_STATUS = (
+ (0, 'Draft'),
+ (1, 'Published'),
+ )
status = models.IntegerField(choices=PUB_STATUS, default=0)
photo_gallery = models.ForeignKey(PhotoGallery, blank=True, null=True, verbose_name='photo set')
- image = models.FileField(upload_to=get_upload_path, null=True,blank=True)
- thumbnail = models.FileField(upload_to=get_tn_path, null=True,blank=True)
+ image = models.FileField(upload_to=get_upload_path, null=True, blank=True)
+ thumbnail = models.FileField(upload_to=get_tn_path, null=True, blank=True)
meta_description = models.CharField(max_length=256, null=True, blank=True)
+ TEMPLATES = (
+ (0, 'single'),
+ (1, 'double'),
+ (2, 'single-dark'),
+ (3, 'double-dark'),
+ (4, 'bigimg'),
+ (5, 'bigimg-dark'),
+ )
template_name = models.IntegerField(choices=TEMPLATES, default=0)
class Meta:
@@ -73,35 +75,35 @@ class Entry(models.Model):
get_latest_by = 'pub_date'
verbose_name_plural = 'entries'
- def __unicode__(self):
+ def __str__(self):
return self.title
def get_absolute_url(self):
return "/%s/%s/" % (self.pub_date.strftime("%Y/%b/%d").lower(), self.slug)
-
+
def comment_period_open(self):
return self.enable_comments and datetime.datetime.today() - datetime.timedelta(30) <= self.pub_date
-
+
def get_thumbnail_url(self):
image_dir, img = self.thumbnail.url.split('post-thumbnail/')[1].split('/')
- return '%spost-thumbnail/%s/%s' %(settings.IMAGES_URL, image_dir, img)
-
+ return '%spost-thumbnail/%s/%s' % (settings.IMAGES_URL, image_dir, img)
+
def get_image_url(self):
image_dir, img = self.image.url.split('post-images/')[1].split('/')
- return '%spost-images/%s/%s' %(settings.IMAGES_URL, image_dir, img)
+ return '%spost-images/%s/%s' % (settings.IMAGES_URL, image_dir, img)
@property
def state(self):
return self.location.state
-
+
@property
def country(self):
return self.location.state.country
-
+
@property
def region(self):
return self.location.state.country.lux_region
-
+
@property
def longitude(self):
'''Get the site's longitude.'''
@@ -110,34 +112,33 @@ class Entry(models.Model):
@property
def latitude(self):
'''Get the site's latitude.'''
- return self.point.y
-
+ return self.point.y
+
@property
def get_previous_published(self):
return self.get_previous_by_pub_date(status__exact=1)
-
- @property
+
+ @property
def get_next_published(self):
return self.get_next_by_pub_date(status__exact=1)
-
- def save(self):
+ def save(self):
md = image_url_replace(self.body_markdown)
- self.body_html = markdown.markdown(md, extensions=['extra',], safe_mode = False)
- self.dek == markdown.markdown(self.dek, safe_mode = False)
+ self.body_html = markdown.markdown(md, extensions=['extra'], safe_mode=False)
+ self.dek == markdown.markdown(self.dek, safe_mode=False)
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))
+ raise forms.ValidationError("There is no location associated with that point, add it: %sadmin/locations/location/add/" % (settings.BASE_URL))
super(Entry, self).save()
+
class EntryAside(models.Model):
title = models.CharField(max_length=200)
- body = models.TextField(null=True,blank=True)
+ body = models.TextField(null=True, blank=True)
entry = models.ForeignKey(Entry)
-
class BlogSitemap(Sitemap):
changefreq = "never"
priority = 1.0
@@ -148,6 +149,7 @@ class BlogSitemap(Sitemap):
def lastmod(self, obj):
return obj.pub_date
+
class LatestFull(Feed):
title = "Luxagraf: Topographical Writings"
link = "/writing/"
diff --git a/app/blog/parse.py b/app/blog/parse.py
index 27f5165..a1e3056 100755
--- a/app/blog/parse.py
+++ b/app/blog/parse.py
@@ -1,12 +1,14 @@
#!/usr/bin/python
-import os, datetime
+import os
+import datetime
from dateutil.parser import parse as dateparser
-from os.path import abspath,dirname
+from os.path import abspath, dirname
from django.core.exceptions import ObjectDoesNotExist
from blog.models import Entry
from django.conf import settings
+
def parse_file(filepath):
data = {}
contents = open(filepath).read()
@@ -15,13 +17,13 @@ def parse_file(filepath):
if line == '---':
break
else:
- k,v = line.split(':', 1)
+ k, v = line.split(':', 1)
data[k.strip()] = v.strip()
body = "\n".join(line.strip() for line in raw[1:])
data["body_markdown"] = body.split('---')[1]
return data
-"""
+"""
now I need a function to query the db for the title and date
if there's no entry then it's new and we add it and publish
What about edits though? Crap, edits. That means we need to check lastmod
@@ -30,23 +32,25 @@ from blog.parse import *
crawl_dir()
"""
+
+
def crawl_dir():
file_root = settings.POSTS_DIR
file_list = os.listdir(file_root)
- file_list = filter(lambda item: not (item.startswith('README') or item.startswith('updategithub.php') or item.startswith('.') or item.endswith('~')),file_list)
- for f in file_list:
- fpath = file_root+"/"+f
+ file_list = filter(lambda item: not (item.startswith('README') or item.startswith('updategithub.php') or item.startswith('.') or item.endswith('~')), file_list)
+ for f in file_list:
+ fpath = file_root + "/" + f
last_mod = datetime.datetime.fromtimestamp(os.path.getmtime(fpath))
- last_run = datetime.datetime.fromtimestamp(os.path.getmtime(abspath(dirname(__file__))+'/last_run'))
- if last_mod > last_run:
+ last_run = datetime.datetime.fromtimestamp(os.path.getmtime(abspath(dirname(__file__)) + '/last_run'))
+ if last_mod > last_run:
print "needs an update"
data = parse_file(fpath)
date = dateparser(data['pub_date'])
try:
- row = Entry.objects.get(title=str(data['title']),pub_date=date)
+ row = Entry.objects.get(title=str(data['title']), pub_date=date)
print row.title, date
except ObjectDoesNotExist:
print data['title'] + str(date) + " = not found"
- last_mod_dump = open(abspath(dirname(__file__))+'/last_run','w')
+ last_mod_dump = open(abspath(dirname(__file__)) + '/last_run', 'w')
print last_mod_dump
print >> last_mod_dump, str(datetime.datetime.now())
diff --git a/app/blog/urls.py b/app/blog/urls.py
index a94eef3..d0a5224 100644
--- a/app/blog/urls.py
+++ b/app/blog/urls.py
@@ -1,10 +1,8 @@
from django.conf.urls import *
from django.views.generic.base import RedirectView
-from blog.models import Entry
urlpatterns = patterns('',
-
(r'(?P<slug>[-\w]+)/(?P<page>\d+)/$', 'blog.views.entry_list_by_area'),
(r'(?P<page>\d+)/$', 'blog.views.entry_list'),
(r'(?P<slug>[-\w]+)/$', RedirectView.as_view(url="/writing/%(slug)s/1/")),
diff --git a/app/blog/views.py b/app/blog/views.py
index 04564fc..8c86839 100644
--- a/app/blog/views.py
+++ b/app/blog/views.py
@@ -1,28 +1,28 @@
-from django.shortcuts import render_to_response,get_object_or_404
+from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from django.http import Http404
from django.conf import settings
-from django.views.generic import ListView
+# from django.views.generic import ListView
from blog.models import Entry
from locations.models import Region, Country
-from photos.models import Photo, PhotoGallery
+from photos.models import Photo
+
def home(request):
context = {
'object_list': Entry.objects.filter(status__exact=1).select_related()[:4]
- }
- return render_to_response('archives/homepage.html', context, context_instance = RequestContext(request))
+ }
+ return render_to_response('archives/homepage.html', context, context_instance=RequestContext(request))
def entry_detail(request, year, month, day, slug):
obj = get_object_or_404(Entry, slug__exact=slug)
photos = {}
- #if obj.photo_gallery:
+ # if obj.photo_gallery:
# photos = Photo.objects.filter(set__exact=obj.get().photo_gallery.id)[:9]
- extra = {'photos':photos,}
- return render_to_response('details/entry.html', {'object': obj,'photos':photos}, context_instance=RequestContext(request))
-
+ extra = {'photos': photos, }
+ return render_to_response('details/entry.html', {'object': obj, 'photos': photos}, context_instance=RequestContext(request))
"""
List of all writing
@@ -39,35 +39,35 @@ class BlogEntryListView(ListView):
return context
"""
-def entry_list(request,page):
+
+
+def entry_list(request, page):
request.page_url = '/writing/%d/'
request.page = int(page)
try:
- is_build = request.POST['builder']
- extra_context={
- 'page':page,
+ extra_context = {
+ 'page': page,
'MEDIA_URL': settings.BAKED_MEDIA_URL
}
except:
- extra_context={'page':page}
+ extra_context = {'page': page}
context = {
'object_list': Entry.objects.filter(status__exact=1).order_by('-pub_date').select_related(),
}
return render_to_response("archives/writing.html", context, context_instance=RequestContext(request))
-"""
-Grabs entries by region or country
-"""
-def entry_list_by_area(request,slug,page):
- request.page_url = '/writing/'+slug+'/%d/'
+def entry_list_by_area(request, slug, page):
+ """ Grabs entries by region or country"""
+ request.page_url = '/writing/' + slug + '/%d/'
request.page = int(page)
try:
region = Region.objects.get(slug__exact=slug)
- qs = Entry.objects.filter(status__exact=1,region = region).order_by('-pub_date')
+ qs = Entry.objects.filter(status__exact=1, region=region).order_by('-pub_date')
except:
region = Country.objects.get(slug__exact=slug)
- qs = Entry.objects.filter(status__exact=1,location__state__country = region).order_by('-pub_date')
+ qs = Entry.objects.filter(
+ status__exact=1, location__state__country=region).order_by('-pub_date')
if not region:
raise Http404
context = {
@@ -75,13 +75,3 @@ def entry_list_by_area(request,slug,page):
'object_list': qs,
}
return render_to_response("archives/writing.html", context, context_instance=RequestContext(request))
-
-"""
-def about(request):
- qs = Chunk.objects.filter(key__in=['about_top','about_middle','about_bottom'])
- context = {
- 'object_list':qs,
- 'IMAGES_URL' : settings.IMAGES_URL
- }
- return render_to_response('details/about.html', context, context_instance=RequestContext(request))
-"""
diff --git a/app/blog/widgets.py b/app/blog/widgets.py
index 64509c2..ec1bd1d 100644
--- a/app/blog/widgets.py
+++ b/app/blog/widgets.py
@@ -1,15 +1,15 @@
+import os
from django.contrib.admin.widgets import AdminFileWidget
-from django.utils.translation import ugettext as _
from django.utils.safestring import mark_safe
from django.conf import settings
-from PIL import Image
-import os
+
def thumbnail(image_path):
absolute_url = os.path.join(settings.IMAGES_URL, image_path[7:])
print(absolute_url)
return '<img style="max-width: 400px" src="%s" alt="%s" />' % (absolute_url, image_path)
+
class AdminImageWidget(AdminFileWidget):
"""
A FileField Widget that displays an image instead of a file path
@@ -21,6 +21,6 @@ class AdminImageWidget(AdminFileWidget):
if file_name:
file_path = '%s' % (file_name)
output.append('<a target="_blank" href="%s">%s</a>' % (file_path, thumbnail(file_name)))
-
+
output.append(super(AdminFileWidget, self).render(name, value, attrs))
return mark_safe(''.join(output))