summaryrefslogtreecommitdiff
path: root/apps
diff options
context:
space:
mode:
authorluxagraf <sng@luxagraf.net>2012-09-22 22:27:04 -0400
committerluxagraf <sng@luxagraf.net>2012-09-22 22:27:04 -0400
commitefb623af0bcb47d510501c282e1326b11343a29c (patch)
tree3a35fb19f5eba3b219c65277a5fb712cbe9604ac /apps
parent0b481fd7931c2ae20ca21f89a87f2ba6a6c01e10 (diff)
site reorg
Diffstat (limited to 'apps')
-rw-r--r--apps/blog/__init__.py0
-rw-r--r--apps/blog/admin.py80
-rw-r--r--apps/blog/fields.py7
-rw-r--r--apps/blog/models.py180
-rw-r--r--apps/blog/signals.py21
-rw-r--r--apps/blog/urls.py15
-rw-r--r--apps/blog/views.py80
-rw-r--r--apps/blog/widgets.py32
-rw-r--r--apps/build/__init__.py0
-rw-r--r--apps/build/admin.py80
-rw-r--r--apps/build/base.py241
-rw-r--r--apps/build/models.py156
-rw-r--r--apps/guide/__init__.py0
-rw-r--r--apps/guide/admin.py63
-rw-r--r--apps/guide/models.py135
-rw-r--r--apps/guide/urls.py11
-rw-r--r--apps/guide/views.py34
-rw-r--r--apps/links/__init__.py0
-rw-r--r--apps/links/admin.py14
-rw-r--r--apps/links/detail_urls.py13
-rw-r--r--apps/links/models.py76
-rw-r--r--apps/links/retriever.py111
-rw-r--r--apps/links/tumblr.py240
-rw-r--r--apps/links/urls.py15
-rw-r--r--apps/locations/__init__.py0
-rw-r--r--apps/locations/admin.py295
-rw-r--r--apps/locations/models.py190
-rw-r--r--apps/locations/urls.py7
-rw-r--r--apps/locations/views.py25
-rw-r--r--apps/photos/__init__.py0
-rw-r--r--apps/photos/admin.py67
-rw-r--r--apps/photos/detail_urls.py10
-rw-r--r--apps/photos/models.py201
-rw-r--r--apps/photos/retriever.py512
-rw-r--r--apps/photos/urls.py13
-rw-r--r--apps/photos/views.py50
-rw-r--r--apps/projects/__init__.py0
-rw-r--r--apps/projects/admin.py182
-rw-r--r--apps/projects/models/__init__.py4
-rw-r--r--apps/projects/models/base.py75
-rw-r--r--apps/projects/models/code.py25
-rw-r--r--apps/projects/models/fiveby.py58
-rw-r--r--apps/projects/models/natparks.py56
-rw-r--r--apps/projects/shortcuts.py235
-rw-r--r--apps/projects/urls.py17
-rw-r--r--apps/projects/views.py38
46 files changed, 0 insertions, 3664 deletions
diff --git a/apps/blog/__init__.py b/apps/blog/__init__.py
deleted file mode 100644
index e69de29..0000000
--- a/apps/blog/__init__.py
+++ /dev/null
diff --git a/apps/blog/admin.py b/apps/blog/admin.py
deleted file mode 100644
index cae0b59..0000000
--- a/apps/blog/admin.py
+++ /dev/null
@@ -1,80 +0,0 @@
-from django.contrib import admin
-from django import forms
-from blog.models import Entry, PostImage, Topic
-from blog.widgets import AdminImageWidget
-from django.contrib.gis.admin import OSMGeoAdmin
-from django.contrib.gis.maps.google import GoogleMap
-from django.conf import settings
-
-
-
-GMAP = GoogleMap(key=settings.GOOGLE_MAPS_API_KEY)
-
-class EntryAdmin(OSMGeoAdmin):
- def formfield_for_dbfield(self, db_field, **kwargs):
- if db_field.name == 'thumbnail':
- field = forms.FileField(widget=AdminImageWidget)
- else:
- field = super(EntryAdmin,self).formfield_for_dbfield(db_field,**kwargs)
- return field
- 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','region','location')
- fieldsets = (
- ('Entry', {'fields': ('title','body_markdown', ('location','region'), 'pub_date', ('status','enable_comments'), 'slug','photo_gallery'), 'classes': ('show','extrapretty','wide')}),
- ('Pub Location', {'fields': ('point',('image','thumbnail',),'dek', 'topics', 'meta_description','template_name'), 'classes': ('collapse', 'wide')}),
- )
-
- class Media:
- js = ['/media/admin/custom/model.js']
- extra_js = [GMAP.api_url + GMAP.key]
- map_template = 'gis/admin/google.html'
- #map_template = 'gis/admin/google.html'
- # Default GeoDjango OpenLayers map options
- # Uncomment and modify as desired
- # To learn more about this jargon visit:
- # www.openlayers.org
-
- default_lon = -9314310
- default_lat = 3991847
- default_zoom = 6
- #display_wkt = False
- #display_srid = False
- #extra_js = []
- #num_zoom = 18
- #max_zoom = False
- #min_zoom = False
- #units = False
- #max_resolution = False
- #max_extent = False
- #modifiable = True
- #mouse_position = True
- #scale_text = True
- #layerswitcher = True
- scrollable = False
- #admin_media_prefix = settings.ADMIN_MEDIA_PREFIX
- map_width = 700
- map_height = 325
- #map_srid = 4326
- #map_template = 'gis/admin/openlayers.html'
- #openlayers_url = 'http://openlayers.org/api/2.6/OpenLayers.js'
- #wms_url = 'http://labs.metacarta.com/wms/vmap0'
- #wms_layer = 'basic'
- #wms_name = 'OpenLayers WMS'
- #debug = False
- #widget = OpenLayersWidget
-
-
-
-
-
-class PostImageAdmin(admin.ModelAdmin):
- list_display = ('title', 'output_tags')
-
-class TopicAdmin(admin.ModelAdmin):
- list_display = ('name', 'slug')
-
-admin.site.register(Topic, TopicAdmin)
-admin.site.register(PostImage, PostImageAdmin)
-admin.site.register(Entry, EntryAdmin)
diff --git a/apps/blog/fields.py b/apps/blog/fields.py
deleted file mode 100644
index bab8ad3..0000000
--- a/apps/blog/fields.py
+++ /dev/null
@@ -1,7 +0,0 @@
-from django import forms
-from blog.widgets import AdminImageWidget
-
-
-class FileUploadForm(forms.ModelForm):
- upload = forms.FileField(widget=AdminImageWidget)
-
diff --git a/apps/blog/models.py b/apps/blog/models.py
deleted file mode 100644
index 37841fe..0000000
--- a/apps/blog/models.py
+++ /dev/null
@@ -1,180 +0,0 @@
-import datetime
-from django.contrib.gis.db import models
-from django.conf import settings
-from django.contrib.syndication.feeds import Feed
-from django.contrib.sitemaps import Sitemap
-from django.template.defaultfilters import truncatewords_html
-from PIL import Image
-
-from utils import markdown2 as markdown
-
-from photos.models import PhotoGallery
-from locations.models import Location,Region
-#from locations.signals import create_location_item
-from blog.signals import update_recent
-
-def get_upload_path(self, 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)
-
-def image_url_replace(str):
- str = str.replace('[[base_url]]', settings.IMAGES_URL)
- return str
-
-def markdown_processor(md):
- processed = markdown.markdown(md, ['footnotes'],safe_mode = False).split('<break>')
- html = processed[0]+processed[1]
- lede = processed[0]
- return html, lede
-
-PUB_STATUS = (
- (0, 'Draft'),
- (1, 'Published'),
- )
-
-TEMPLATES = (
- (0, 'single'),
- (1, 'double'),
- (2, 'single-dark'),
- (3, 'double-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")))
-
- def __unicode__(self):
- return self.title
-
- def output_tags(self):
- return force_unicode('<img src="%s%s" alt="%s" class="postpic"/>' % \
- (settings.IMAGES_URL, self.image.url.split('images')[1].split('/',1)[1], self.title))
-
-
-class Topic(models.Model):
- name = models.CharField(max_length=100)
- slug = models.SlugField()
-
- def __unicode__(self):
- return self.name
-
- def get_absolute_url(self):
- return "/topics/%s/" % (self.slug)
-
-class Entry(models.Model):
- title = models.CharField(max_length=200)
- slug = models.SlugField(unique_for_date='pub_date')
- lede = models.TextField(blank=True)
- body_html = models.TextField(blank=True)
- body_markdown = models.TextField()
- dek = models.TextField(null=True,blank=True)
- pub_date = models.DateTimeField('Date published')
- enable_comments = models.BooleanField(default=True)
- point = models.PointField(null=True, blank=True)
- location = models.ForeignKey(Location, null=True)
- region = models.ForeignKey(Region, null=True)
- 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)
- image_height = models.CharField(max_length=20, null=True,blank=True)
- image_width = models.CharField(max_length=20, null=True,blank=True)
- thumbnail = models.FileField(upload_to=get_tn_path, null=True,blank=True)
- thumb_height = models.CharField(max_length=20, null=True,blank=True)
- thumb_width = models.CharField(max_length=20, null=True,blank=True)
- meta_description = models.CharField(max_length=256, null=True, blank=True)
- topics = models.ManyToManyField(Topic, blank=True)
- template_name = models.IntegerField(choices=TEMPLATES, default=0)
- location_name = models.CharField(max_length=200, null=True,blank=True)
- state_name = models.CharField(max_length=200, null=True,blank=True)
- country_name = models.CharField(max_length=200, null=True,blank=True)
- state_iso = models.CharField(max_length=2, null=True,blank=True)
- country_iso = models.CharField(max_length=2, null=True,blank=True)
-
- @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
-
- class Meta:
- ordering = ('-pub_date',)
- get_latest_by = 'pub_date'
- verbose_name_plural = 'entries'
-
- def __unicode__(self):
- return self.title
-
- def get_absolute_url(self):
- return "/%s/%s/" % (self.pub_date.strftime("%Y/%b/%d").lower(), self.slug)
-
- @property
- def get_previous_published(self):
- return self.get_previous_by_pub_date(status__exact=1)
-
- @property
- def get_next_published(self):
- return self.get_next_by_pub_date(status__exact=1)
-
-
- 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)
-
- 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)
-
- def save(self):
- #get image dimensions
- img = Image.open(self.image)
- self.image_width, self.image_height = img.size
- #same for thumb
- img = Image.open(self.thumbnail)
- self.thumb_width, self.thumb_height = img.size
- #find and replace image urls
- md = image_url_replace(self.body_markdown)
- #run markdown
- html,lede = markdown_processor(md)
- self.body_html = html
- self.lede = lede
- self.dek == markdown.markdown(self.dek, safe_mode = False)
- self.location_name = self.location.name
- self.state_name = self.location.state.name
- self.country_name = self.location.state.country.name
- self.state_iso = self.location.state.code
- self.country_iso = self.location.state.country.iso2
- super(Entry, self).save()
-
-class BlogSitemap(Sitemap):
- changefreq = "never"
- priority = 1.0
-
- def items(self):
- return Entry.objects.filter(status=1)
-
- def lastmod(self, obj):
- return obj.pub_date
-
-class LatestFull(Feed):
- title = "Luxagraf: Topographical Writings"
- link = "/writing/"
- description = "Latest postings to luxagraf.net"
- description_template = 'feeds/blog_description.html'
-
- def items(self):
- return Entry.objects.filter(status__exact=1).order_by('-pub_date')[:10]
-
-
-from django.dispatch import dispatcher
-from django.db.models import signals
-
-signals.post_save.connect(update_recent, sender=Entry)
-
diff --git a/apps/blog/signals.py b/apps/blog/signals.py
deleted file mode 100644
index a8c0556..0000000
--- a/apps/blog/signals.py
+++ /dev/null
@@ -1,21 +0,0 @@
-from django.template.loader import render_to_string
-from django.conf import settings
-from django.template import Context
-from django.db.models import get_model
-from django.conf import settings
-
-from locations.models import Region,Country,Route
-
-from build.base import BuildWriting,BuildMap
-
-def update_recent(sender, instance, signal, *args, **kwargs):
- if not settings.DEVELOPMENT:
- if instance.status == 1:
- #update homepage, archives and details
- b = BuildWriting()
- b.build_homepage()
- b.build_archive_pages()
- b.build_detail_pages()
- #update map
- b = BuildMap()
- b.build() \ No newline at end of file
diff --git a/apps/blog/urls.py b/apps/blog/urls.py
deleted file mode 100644
index 57a3e7a..0000000
--- a/apps/blog/urls.py
+++ /dev/null
@@ -1,15 +0,0 @@
-from django.conf.urls.defaults import *
-from django.views.generic.list_detail import object_list
-from django.views.generic.simple import redirect_to
-
-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]+)/$', redirect_to, {'url': '/writing/%(slug)s/1/'}),
- (r'', redirect_to, {'url': '/writing/1/'}),
-)
diff --git a/apps/blog/views.py b/apps/blog/views.py
deleted file mode 100644
index 72c769e..0000000
--- a/apps/blog/views.py
+++ /dev/null
@@ -1,80 +0,0 @@
-from django.shortcuts import render_to_response,get_object_or_404
-from django.template import RequestContext
-from django.views.generic.date_based import object_detail
-from django.views.generic.list_detail import object_list
-from django.http import Http404
-from django.conf import settings
-
-
-from blog.models import Entry, Topic
-from locations.models import Region, Country
-from photos.models import Photo, PhotoGallery
-from chunks.models import Chunk
-
-def home(request):
- featured = Entry.objects.filter(status__exact=1).select_related().latest()
- #gallery = PhotoGallery.objects.latest()
- context = {
- 'featured': featured,
- #'gallery': gallery
- }
- 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:
- # 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))
-
-
-"""
-List of all writing
-"""
-def entry_list(request,page):
- request.page_url = '/writing/%d/'
- request.page = int(page)
- qs = Entry.objects.filter(status__exact=1).order_by('-pub_date').select_related()
- return object_list(request, queryset=qs, template_name='archives/writing.html', extra_context={'page':page})
-
-
-"""
-List of all writing
-"""
-def topic_list(request,slug,page):
- request.page_url = '/topics/'+slug+'/%d/'
- request.page = int(page)
- topic = Topic.objects.get(slug=slug)
- qs = Entry.objects.filter(status__exact=1,topics=topic).order_by('-pub_date').select_related()
- return object_list(request, queryset=qs, template_name='archives/topics.html',extra_context={'page':page})
-
-
-"""
-Grabs entries by region or country
-"""
-def entry_list_by_area(request,slug,page):
- 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')
- except:
- region = Country.objects.get(slug__exact=slug)
- qs = Entry.objects.filter(status__exact=1,location__state__country = region).order_by('-pub_date')
- if not region:
- raise Http404
- context = {
- 'region': region,
- }
- return object_list(request, queryset=qs, template_name='archives/writing.html',
- extra_context=context)
-
-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)) \ No newline at end of file
diff --git a/apps/blog/widgets.py b/apps/blog/widgets.py
deleted file mode 100644
index a9451e7..0000000
--- a/apps/blog/widgets.py
+++ /dev/null
@@ -1,32 +0,0 @@
-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
-
-try:
- from sorl.thumbnail.main import DjangoThumbnail
- def thumbnail(image_path):
- t = DjangoThumbnail(relative_source=image_path, requested_size=(200,200))
- return u'<img src="%s" alt="%s" />' % (t.absolute_url, image_path)
-except ImportError:
- def thumbnail(image_path):
- absolute_url = os.path.join(settings.IMAGES_URL, image_path)
- return u'<img src="%s" alt="%s" />' % (absolute_url, image_path)
-
-class AdminImageWidget(AdminFileWidget):
- """
- A FileField Widget that displays an image instead of a file path
- if the current file is an image.
- """
- def render(self, name, value, attrs=None):
- output = []
- file_name = str(value)
- if file_name:
- file_path = '%s' % (file_name)
- output.append('<a target="_blank" href="%s">%s</a><br />%s <a target="_blank" href="%s">%s</a><br />%s ' % \
- (file_path, thumbnail(file_name), _('Currently:'), file_path, file_name, _('Change:')))
-
- output.append(super(AdminFileWidget, self).render(name, value, attrs))
- return mark_safe(u''.join(output))
diff --git a/apps/build/__init__.py b/apps/build/__init__.py
deleted file mode 100644
index e69de29..0000000
--- a/apps/build/__init__.py
+++ /dev/null
diff --git a/apps/build/admin.py b/apps/build/admin.py
deleted file mode 100644
index ee6957e..0000000
--- a/apps/build/admin.py
+++ /dev/null
@@ -1,80 +0,0 @@
-from django.contrib import admin
-from django import forms
-from blog.models import Entry, PostImage, Topic
-from blog.widgets import AdminImageWidget
-from django.contrib.gis.admin import OSMGeoAdmin
-from django.contrib.gis.maps.google import GoogleMap
-from django.conf import settings
-
-
-
-GMAP = GoogleMap(key=settings.GOOGLE_MAPS_API_KEY)
-
-class EntryAdmin(OSMGeoAdmin):
- def formfield_for_dbfield(self, db_field, **kwargs):
- if db_field.name == 'thumbnail':
- field = forms.FileField(widget=AdminImageWidget)
- else:
- field = super(EntryAdmin,self).formfield_for_dbfield(db_field,**kwargs)
- return field
- list_display = ('title', 'pub_date','enable_comments', 'status','region','location','photo_gallery')
- search_fields = ['title', 'body_markdown']
- prepopulated_fields = {"slug" : ('title',)}
- list_filter = ('pub_date', 'enable_comments', 'status','region','location')
- fieldsets = (
- ('Entry', {'fields': ('title','body_markdown', ('location','region'), 'pub_date', ('status','enable_comments'), 'slug','photo_gallery'), 'classes': ('show','extrapretty','wide')}),
- ('Pub Location', {'fields': ('point',('image','thumbnail',),'dek', 'topics', 'meta_description','template_name'), 'classes': ('collapse', 'wide')}),
- )
-
- class Media:
- js = ['/media/admin/custom/model.js']
- extra_js = [GMAP.api_url + GMAP.key]
- map_template = 'gis/admin/google.html'
- #map_template = 'gis/admin/google.html'
- # Default GeoDjango OpenLayers map options
- # Uncomment and modify as desired
- # To learn more about this jargon visit:
- # www.openlayers.org
-
- default_lon = -9314310
- default_lat = 3991847
- default_zoom = 6
- #display_wkt = False
- #display_srid = False
- #extra_js = []
- #num_zoom = 18
- #max_zoom = False
- #min_zoom = False
- #units = False
- #max_resolution = False
- #max_extent = False
- #modifiable = True
- #mouse_position = True
- #scale_text = True
- #layerswitcher = True
- scrollable = False
- #admin_media_prefix = settings.ADMIN_MEDIA_PREFIX
- map_width = 700
- map_height = 325
- #map_srid = 4326
- #map_template = 'gis/admin/openlayers.html'
- #openlayers_url = 'http://openlayers.org/api/2.6/OpenLayers.js'
- #wms_url = 'http://labs.metacarta.com/wms/vmap0'
- #wms_layer = 'basic'
- #wms_name = 'OpenLayers WMS'
- #debug = False
- #widget = OpenLayersWidget
-
-
-
-
-
-class PostImageAdmin(admin.ModelAdmin):
- list_display = ('title', 'output_tags')
-
-class TopicAdmin(admin.ModelAdmin):
- list_display = ('name', 'slug')
-
-admin.site.register(Topic, TopicAdmin)
-admin.site.register(PostImage, PostImageAdmin)
-admin.site.register(Entry, EntryAdmin)
diff --git a/apps/build/base.py b/apps/build/base.py
deleted file mode 100644
index f6df69d..0000000
--- a/apps/build/base.py
+++ /dev/null
@@ -1,241 +0,0 @@
-import os
-from math import ceil
-from decimal import Decimal
-from django.test.client import Client
-from django.template.loader import render_to_string
-from django.conf import settings
-from django.template import Context
-from django.db.models import get_model
-from django.conf import settings
-
-
-class Build():
- def write_file(self, path, object):
- file = open(path, 'w')
- file.write(object)
- file.close()
-
-class BuildSitemap(Build):
- def build(self):
- c = Client()
- response = c.get('/sitemap.xml')
- fpath = '%ssitemap.xml' %(settings.BAKED_ROOT)
- self.write_file(fpath,str(response.content))
-
-class BuildWriting(Build):
-
-
- def build(self):
- self.build_detail_pages()
- self.build_archive_pages()
- self.build_location_archive_pages()
- self.build_homepage()
-
- def get_model_querset(self):
- model = get_model('blog', 'entry')
- qs = model.objects.filter(status__exact=1)
- return qs
-
- def build_detail_pages(self):
- '''
- Grab all the blog posts, render them to a template string and write that out to the filesystem
- '''
- qs = self.get_model_querset()
- for entry in qs:
- c = Context({'object':entry,'MEDIA_URL':settings.BAKED_MEDIA_URL, 'IMAGES_URL':settings.BAKED_IMAGES_URL})
- t = render_to_string('details/entry.html',c).encode('utf-8')
- path = '%s%s/%s/' %(settings.BAKED_ROOT, entry.pub_date.strftime("%Y/%b/%d").lower(), entry.slug)
- if not os.path.isdir(path):
- os.makedirs(path)
- fpath = '%sindex.html' %(path)
- self.write_file(fpath,t)
-
- def build_archive_pages(self, qs=None, extra='writing/', paginate_by=10):
- if qs == None:
- qs = self.get_model_querset()
- c = Client()
- pages = ceil(Decimal(qs.count())/Decimal(paginate_by))
- print pages
- for page in range(int(pages)):
- base_path = '%s%s' %(settings.BAKED_ROOT, extra)
- path = '%s%s/' %(base_path, page+1)
- if not os.path.isdir(path):
- os.makedirs(path)
- url = '/%s%s/' %(extra, str(page+1))
- page_url = extra+'%d/'
- response = c.post(url, {'page_url': page_url, 'page': int(page)})
- fpath = '%sindex.html' %(path)
- if page == 0:
- self.write_file(base_path+'/index.html',str(response.content))
- self.write_file(fpath,str(response.content))
-
- def build_location_archive_pages(self):
- model = get_model('locations', 'Country')
- blog = get_model('blog', 'entry')
- countries = model.objects.filter(visited=True)
- for c in countries:
- qs = blog.objects.filter(status__exact=1,location__state__country = c).order_by('-pub_date')
- path = 'writing/%s/' %(c.slug)
- self.build_archive_pages(qs, path)
-
- def build_recent_entries(self):
- model = get_model('blog', 'entry')
- qs = {'object_list': model.objects.filter(status__exact=1).order_by('-pub_date')[1:4]}
- c = Context(qs)
- t = render_to_string('bin/recent_entries.html',c).encode('utf-8')
- fpath = '%s%s' %(settings.PROJ_ROOT,'templates/includes/recent_entries.html')
- self.write_file(fpath,t)
-
-
-
- def build_homepage(self):
- self.build_recent_entries()
- qs = get_model('blog', 'entry').objects.filter(status__exact=1).latest()
- c = Context({'featured':qs,'MEDIA_URL':settings.BAKED_MEDIA_URL, 'IMAGES_URL':settings.BAKED_IMAGES_URL})
- t = render_to_string('archives/homepage.html',c).encode('utf-8')
- fpath = '%s%s' %(settings.BAKED_ROOT,'index.html')
- self.write_file(fpath,t)
-
-
-class BuildPhotos(BuildWriting):
-
- def build(self):
- self.build_photo_archive_pages()
- self.build_detail_pages()
-
- def build_photo_archive_pages(self):
- qs = get_model('photos', 'PhotoGallery').objects.all()
- path = 'photos/'
- self.build_archive_pages(qs, path, 18)
-
- def build_detail_pages(self):
- qs = get_model('photos', 'PhotoGallery').objects.all()
- path = 'photos/galleries/'
- '''
- Grab all the blog posts, render them to a template string and write that out to the filesystem
- '''
- for photo in qs:
- c = Context({'object':photo,'MEDIA_URL':settings.BAKED_MEDIA_URL, 'IMAGES_URL':settings.BAKED_IMAGES_URL})
- t = render_to_string('details/photo_galleries.html',c).encode('utf-8')
- path = '%sphotos/galleries/%s/' %(settings.BAKED_ROOT, photo.set_slug)
- if not os.path.isdir(path):
- os.makedirs(path)
- fpath = '%sindex.html' %(path)
- self.write_file(fpath,t)
-
-
-
-class BuildAbout(Build):
- def build(self):
- model = get_model('chunks', 'Chunk')
- qs = model.objects.filter(key__in=['about_top','about_middle','about_bottom'])
- c = Context({
- 'object_list': qs,
- 'IMAGES_URL' : settings.BAKED_IMAGES_URL,
- 'MEDIA_URL':settings.BAKED_MEDIA_URL
- })
- t = render_to_string('details/about.html',c).encode('utf-8')
- path = '%sabout/' %(settings.BAKED_ROOT)
- if not os.path.isdir(path):
- os.makedirs(path)
- fpath = '%sindex.html' %(path)
- self.write_file(fpath,t)
-
-class BuildMap(Build):
-
- def build_map_templates(self):
- import codecs
- qs = get_model('blog', 'entry').objects.filter(status__exact=1)
- cl = get_model('locations', 'Country').objects.filter(visited=True).exclude(name='default')
- rl = get_model('locations', 'Region').objects.all()
- rtl = get_model('locations', 'Route').objects.all()
- c = Context({'object_list':qs, 'country_list':cl,'region_list':rl, 'route_list':rtl, 'MEDIA_URL':settings.BAKED_MEDIA_URL, 'IMAGES_URL':settings.BAKED_IMAGES_URL})
- t = render_to_string('bin/map_entry_list.html',c).encode('utf-8')
- fpath = '%s%s' %(settings.PROJ_ROOT,'media/js/mainmap.js')
- self.write_file(fpath,t)
- c = Context({'country_list':cl,'region_list':rl,'route_list':rtl,'MEDIA_URL':settings.BAKED_MEDIA_URL, 'IMAGES_URL':settings.BAKED_IMAGES_URL})
- t = render_to_string('bin/map_sidebar.html',c).encode('utf-8')
- fpath = '%s%s' %(settings.PROJ_ROOT,'templates/includes/map_sidebar.html')
- self.write_file(fpath,t)
-
- def build(self):
- self.build_map_templates()
- c = Context({'MEDIA_URL':settings.BAKED_MEDIA_URL,'IMAGES_URL':settings.BAKED_IMAGES_URL})
- t = render_to_string('archives/map.html', c).encode('utf-8')
- path = '%smap/' %(settings.BAKED_ROOT)
- if not os.path.isdir(path):
- os.makedirs(path)
- fpath = '%sindex.html' %(path)
- self.write_file(fpath,t)
-
-class BuildContact(Build):
- def build(self):
- c = Client()
- response = c.get('/contact/')
- path = '%scontact/' %(settings.BAKED_ROOT)
- if not os.path.isdir(path):
- os.makedirs(path)
- fpath = '%sindex.html' %(path)
- self.write_file(fpath,str(response.content))
-
-class BuildProjects(Build):
-
- def build(self):
- self.build_project_archive()
- self.build_project_details()
- self.build_project_data()
-
- def get_projects(self):
- all_proj = []
- projects = get_model('projects', 'Project').objects.filter(status__exact=1).order_by('-pub_date')
- for proj in projects:
- row = {'slug':proj.slug, 'name':proj.model_name}
- all_proj.append(row)
- return all_proj
-
- def build_project_archive(self):
- qs = get_model('projects', 'Project').objects.filter(status__exact=1).order_by('-pub_date')
- c = Context({'object_list': qs,'MEDIA_URL':settings.BAKED_MEDIA_URL,'IMAGES_URL':settings.BAKED_IMAGES_URL})
- t = render_to_string('archives/projects.html', c).encode('utf-8')
- path = '%sprojects/' %(settings.BAKED_ROOT)
- if not os.path.isdir(path):
- os.makedirs(path)
- fpath = '%sindex.html' %(path)
- self.write_file(fpath,t)
-
- def build_project_details(self):
- projects = self.get_projects()
- for proj in projects:
- model = get_model('projects', proj['name'])
- if proj['name'] == 'NationalParks':
- qs = model.objects.filter(visited__exact=True).order_by("-date_visited_begin")
- else:
- qs = model.objects.filter(status__exact=1)
- c = Context({'object_list': qs,'MEDIA_URL':settings.BAKED_MEDIA_URL,'IMAGES_URL':settings.BAKED_IMAGES_URL})
- t = render_to_string('details/%s.html' %(proj['slug']), c).encode('utf-8')
- path = '%sprojects/%s/' %(settings.BAKED_ROOT, proj['slug'])
- if not os.path.isdir(path):
- os.makedirs(path)
- fpath = '%sindex.html' %(path)
- self.write_file(fpath,t)
- def build_project_data(self):
- from projects.shortcuts import render_to_geojson
- model = get_model('projects', 'NationalParks')
- for park in model.objects.filter(visited__exact=True):
- qs = model.objects.filter(pk=park.id)
- json = render_to_geojson(
- qs,
- included_fields=['id',],
- geom_attribute='mpoly',
- mimetype = 'application/json',
- pretty_print=True
- )
- json = str(json)
- json ="\n".join(json.splitlines()[3:])
- #print json
- path = '%sprojects/data/' %(settings.BAKED_ROOT)
- if not os.path.isdir(path):
- os.makedirs(path)
- fpath = '%s%s.json' %(path, park.id)
- self.write_file(fpath,json)
-
diff --git a/apps/build/models.py b/apps/build/models.py
deleted file mode 100644
index 65c0149..0000000
--- a/apps/build/models.py
+++ /dev/null
@@ -1,156 +0,0 @@
-import datetime
-from django.contrib.gis.db import models
-from django.conf import settings
-from django.contrib.syndication.feeds import Feed
-from django.contrib.sitemaps import Sitemap
-from django.template.defaultfilters import truncatewords_html
-
-
-from utils import markdown2 as markdown
-
-from photos.models import PhotoGallery
-from locations.models import Location,Region
-#from locations.signals import create_location_item
-from blog.signals import update_recent
-
-def get_upload_path(self, 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)
-
-
-def markdown_processor(md):
- processed = markdown.markdown(md, ['footnotes'],safe_mode = False).split('<break>')
- html = processed[0]+processed[1]
- lede = processed[0]
- return html, lede
-
-PUB_STATUS = (
- (0, 'Draft'),
- (1, 'Published'),
- )
-
-TEMPLATES = (
- (0, 'single'),
- (1, 'double'),
- (2, 'single-dark'),
- (3, 'double-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")))
-
- def __unicode__(self):
- return self.title
-
- def output_tags(self):
- return force_unicode('<img src="%s%s" alt="%s" class="postpic"/>' % \
- (settings.IMAGES_URL, self.image.url.split('images')[1].split('/',1)[1], self.title))
-
-
-class Topic(models.Model):
- name = models.CharField(max_length=100)
- slug = models.SlugField()
-
- def __unicode__(self):
- return self.name
-
- def get_absolute_url(self):
- return "/topics/%s/" % (self.slug)
-
-class Entry(models.Model):
- title = models.CharField(max_length=200)
- slug = models.SlugField(unique_for_date='pub_date')
- lede = models.TextField(blank=True)
- body_html = models.TextField(blank=True)
- body_markdown = models.TextField()
- dek = models.TextField(null=True,blank=True)
- pub_date = models.DateTimeField('Date published')
- enable_comments = models.BooleanField(default=True)
- point = models.PointField(null=True)
- location = models.ForeignKey(Location, null=True)
- region = models.ForeignKey(Region, null=True)
- 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)
- meta_description = models.CharField(max_length=256, null=True, blank=True)
- topics = models.ManyToManyField(Topic, blank=True)
- template_name = models.IntegerField(choices=TEMPLATES, default=0)
-
- @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
-
- class Meta:
- ordering = ('-pub_date',)
- get_latest_by = 'pub_date'
- verbose_name_plural = 'entries'
-
- def __unicode__(self):
- return self.title
-
- def get_absolute_url(self):
- return "/%s/%s/" % (self.pub_date.strftime("%Y/%b/%d").lower(), self.slug)
-
- def get_previous_published(self):
- return self.get_previous_by_pub_date(status__exact=1)
-
- def get_next_published(self):
- return self.get_next_by_pub_date(status__exact=1)
-
-
- def comment_period_open(self):
- return self.enable_comments and datetime.datetime.today() - datetime.timedelta(30) <= self.pub_date
-
- def get_thumbnail_url(self):
- if settings.DEVELOPMENT == True:
- return '%s%s' %(settings.IMAGES_URL, self.thumbnail.url[35:])
- else:
- return '%s%s' %(settings.IMAGES_URL, self.thumbnail.url[33:])
-
- def get_image_url(self):
- if settings.DEVELOPMENT == True:
- return '%s%s' %(settings.IMAGES_URL, self.image.url[35:])
- else:
- return '%s%s' %(settings.IMAGES_URL, self.image.url[33:])
-
- def save(self):
- html,lede = markdown_processor(self.body_markdown)
- self.body_html = html
- self.lede = lede
- self.dek == markdown.markdown(self.dek, safe_mode = False)
- super(Entry, self).save()
-
-class BlogSitemap(Sitemap):
- changefreq = "never"
- priority = 1.0
-
- def items(self):
- return Entry.objects.filter(status=1)
-
- def lastmod(self, obj):
- return obj.pub_date
-
-class LatestFull(Feed):
- title = "Luxagraf: Topographical Writings"
- link = "/writing/"
- description = "Latest postings to luxagraf.net"
- description_template = 'feeds/blog_description.html'
-
- def items(self):
- return Entry.objects.filter(status__exact=1).order_by('-pub_date')[:10]
-
-
-from django.dispatch import dispatcher
-from django.db.models import signals
-
-signals.post_save.connect(update_recent, sender=Entry)
-
diff --git a/apps/guide/__init__.py b/apps/guide/__init__.py
deleted file mode 100644
index e69de29..0000000
--- a/apps/guide/__init__.py
+++ /dev/null
diff --git a/apps/guide/admin.py b/apps/guide/admin.py
deleted file mode 100644
index 55f713f..0000000
--- a/apps/guide/admin.py
+++ /dev/null
@@ -1,63 +0,0 @@
-from django.contrib import admin
-from django import forms
-from guide.models import Guide
-from django.contrib.gis.admin import OSMGeoAdmin
-from django.contrib.gis.maps.google import GoogleMap
-from django.conf import settings
-
-
-
-GMAP = GoogleMap(key=settings.GOOGLE_MAPS_API_KEY)
-
-class GuideAdmin(OSMGeoAdmin):
- 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', 'status','region','location')
- fieldsets = (
- ('Note', {'fields': ('title','body_markdown', ('location','region'), 'pub_date', 'status', 'slug','photo_gallery'), 'classes': ('show','extrapretty','wide')}),
- ('Extra', {'fields': ('dek', 'meta_description','template_name', ('image', 'thumbnail')), 'classes': ('collapse', 'wide')}),
- )
-
- class Media:
- js = ['/media/admin/custom/model.js']
- extra_js = [GMAP.api_url + GMAP.key]
- map_template = 'gis/admin/google.html'
- #map_template = 'gis/admin/google.html'
- # Default GeoDjango OpenLayers map options
- # Uncomment and modify as desired
- # To learn more about this jargon visit:
- # www.openlayers.org
-
- default_lon = -9314310
- default_lat = 3991847
- default_zoom = 6
- #display_wkt = False
- #display_srid = False
- #extra_js = []
- #num_zoom = 18
- #max_zoom = False
- #min_zoom = False
- #units = False
- #max_resolution = False
- #max_extent = False
- #modifiable = True
- #mouse_position = True
- #scale_text = True
- #layerswitcher = True
- scrollable = False
- #admin_media_prefix = settings.ADMIN_MEDIA_PREFIX
- map_width = 700
- map_height = 325
- #map_srid = 4326
- #map_template = 'gis/admin/openlayers.html'
- #openlayers_url = 'http://openlayers.org/api/2.6/OpenLayers.js'
- #wms_url = 'http://labs.metacarta.com/wms/vmap0'
- #wms_layer = 'basic'
- #wms_name = 'OpenLayers WMS'
- #debug = False
- #widget = OpenLayersWidget
-
-
-
-admin.site.register(Guide, GuideAdmin)
diff --git a/apps/guide/models.py b/apps/guide/models.py
deleted file mode 100644
index 793b9f4..0000000
--- a/apps/guide/models.py
+++ /dev/null
@@ -1,135 +0,0 @@
-import datetime
-from django.contrib.gis.db import models
-from django.conf import settings
-from django.contrib.syndication.feeds import Feed
-from django.contrib.sitemaps import Sitemap
-from django.template.defaultfilters import truncatewords_html
-from PIL import Image
-
-
-from utils import markdown2 as markdown
-from taggit.managers import TaggableManager
-from locations.models import Location,Region,Country
-from blog.models import Entry
-from photos.models import PhotoGallery
-
-def get_upload_path(self, filename):
- return "images/guide-images/%s/%s" %(datetime.datetime.today().strftime("%Y"), filename)
-
-def get_tn_path(self, filename):
- return "images/guide-thumbnail/%s/%s" %(datetime.datetime.today().strftime("%Y"), filename)
-
-def image_url_replace(str):
- str = str.replace('[[base_url]]', settings.IMAGES_URL)
- return str
-
-def markdown_processor(md):
- return markdown.markdown(md, ['footnotes'],safe_mode = False)
-
-PUB_STATUS = (
- (0, 'Draft'),
- (1, 'Published'),
- )
-
-TEMPLATES = (
- (0, 'single'),
- (1, 'double'),
- (2, 'single-dark'),
- (3, 'double-dark'),
- )
-
-class Guide(models.Model):
- title = models.CharField(max_length=200)
- slug = models.SlugField(unique_for_date='pub_date')
- entry = models.ForeignKey(Entry, null=True, blank=True)
- body_html = models.TextField(blank=True)
- body_markdown = models.TextField()
- dek = models.TextField(null=True,blank=True)
- pub_date = models.DateTimeField('Date published')
- location = models.ForeignKey(Location, null=True, blank=True)
- country = models.ForeignKey(Country, null=True, blank=True)
- region = models.ForeignKey(Region, null=True, blank=True)
- status = models.IntegerField(choices=PUB_STATUS, default=0)
- photo_gallery = models.ForeignKey(PhotoGallery, blank=True, null=True, verbose_name='photo set')
- meta_description = models.CharField(max_length=256, null=True, blank=True)
- template_name = models.IntegerField(choices=TEMPLATES, default=0)
- tags = TaggableManager(blank=True)
- image = models.FileField(upload_to=get_upload_path, null=True,blank=True)
- image_height = models.CharField(max_length=20, null=True,blank=True)
- image_width = models.CharField(max_length=20, null=True,blank=True)
- thumbnail = models.FileField(upload_to=get_tn_path, null=True,blank=True)
- thumb_height = models.CharField(max_length=20, null=True,blank=True)
- thumb_width = models.CharField(max_length=20, null=True,blank=True)
-
-
- @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
-
- class Meta:
- ordering = ('-pub_date',)
- get_latest_by = 'pub_date'
- verbose_name_plural = 'entries'
-
- def __unicode__(self):
- return self.title
-
- def get_absolute_url(self):
- if self.location:
- return "/travel-guide/location/%s/%s/" % (self.location.slug, self.slug)
- else:
- return "/travel-guide/%s/" % (self.slug)
-
- def get_thumbnail_url(self):
- image_dir, img = self.thumbnail.url.split('guide-thumbnail/')[1].split('/')
- return '%sguide-thumbnail/%s/%s' %(settings.IMAGES_URL, image_dir, img)
-
- def get_image_url(self):
- image_dir, img = self.image.url.split('guide-images/')[1].split('/')
- return '%sguide-images/%s/%s' %(settings.IMAGES_URL, image_dir, img)
-
- def save(self):
- #get image dimensions
- if self.image:
- img = Image.open(self.image)
- self.image_width, self.image_height = img.size
- #same for thumb
- img = Image.open(self.thumbnail)
- self.thumb_width, self.thumb_height = img.size
- md = image_url_replace(self.body_markdown)
- #run markdown
- self.body_html = markdown_processor(md)
- self.dek == markdown.markdown(self.dek, safe_mode = False)
- super(Guide, self).save()
-
-class GuideSitemap(Sitemap):
- changefreq = "never"
- priority = 1.0
-
- def items(self):
- return Entry.objects.filter(status=1)
-
- def lastmod(self, obj):
- return obj.pub_date
-
-class GuideFull(Feed):
- title = "Luxagraf: Topographical Writings"
- link = "/writing/"
- description = "Latest postings to luxagraf.net"
- description_template = 'feeds/blog_description.html'
-
- def items(self):
- return Entry.objects.filter(status__exact=1).order_by('-pub_date')[:10]
-
-
-#from django.dispatch import dispatcher
-#from django.db.models import signals
-
-#signals.post_save.connect(update_recent, sender=Entry)
-
diff --git a/apps/guide/urls.py b/apps/guide/urls.py
deleted file mode 100644
index 75a24e5..0000000
--- a/apps/guide/urls.py
+++ /dev/null
@@ -1,11 +0,0 @@
-from django.conf.urls.defaults import *
-from django.views.generic.simple import redirect_to
-
-urlpatterns = patterns('',
- (r'location/(?P<location>[-\w]+)/(?P<slug>[-\w]+)/$', 'guide.views.guide_detail'),
- (r'location/(?P<location>[-\w]+)/$', 'guide.views.guide_list_by_location'),
- (r'location/$', 'guide.views.location_list'),
- (r'(?P<page>\d+)/$', 'guide.views.guide_list'),
- (r'(?P<slug>[-\w]+)/$', 'guide.views.guide_detail'),
- (r'', redirect_to, {'url': '/travel-guide/1/'}),
-)
diff --git a/apps/guide/views.py b/apps/guide/views.py
deleted file mode 100644
index dc63fc5..0000000
--- a/apps/guide/views.py
+++ /dev/null
@@ -1,34 +0,0 @@
-from django.shortcuts import render_to_response,get_object_or_404
-from django.template import RequestContext
-from django.views.generic.list_detail import object_list
-from django.core.exceptions import ObjectDoesNotExist
-
-from guide.models import Guide
-from locations.models import Location
-
-def guide_list(request,page):
- """
- List of all guides
- """
- request.page_url = '/guide/%d/'
- request.page = int(page)
- qs = Guide.objects.filter(status__exact=1).order_by('-pub_date').select_related()
- return object_list(request, queryset=qs, template_name='archives/guide.html', extra_context={'page':page})
-
-def guide_list_by_location(request,location):
- qs = Guide.objects.filter(location__slug__exact=location)
- return object_list(request, queryset=qs, template_name='archives/writing.html')
-
-def location_list(request):
- """
- List of all locations with guides
- """
- qs = Guide.objects.filter(status__exact=1).order_by('-pub_date').select_related()
- return object_list(request, queryset=qs, template_name='archives/guide.html')
-
-def guide_detail(request, slug, location=None):
- obj = get_object_or_404(Guide, slug__exact=slug)
- return render_to_response('details/guide.html', {'object': obj,}, context_instance=RequestContext(request))
-
-
-
diff --git a/apps/links/__init__.py b/apps/links/__init__.py
deleted file mode 100644
index e69de29..0000000
--- a/apps/links/__init__.py
+++ /dev/null
diff --git a/apps/links/admin.py b/apps/links/admin.py
deleted file mode 100644
index 2c73c76..0000000
--- a/apps/links/admin.py
+++ /dev/null
@@ -1,14 +0,0 @@
-from django.contrib import admin
-
-from links.models import Link
-
-class LinkAdmin(admin.ModelAdmin):
- list_display = ('title', 'rating', 'pub_date', 'status')
- search_fields = ['title','description','url']
- list_filter = ['rating', 'status']
- fieldsets = (
- (None, {'fields': ('title','url','description','rating')}),
- ('Details', {'fields': ('screen_url', 'pub_date', 'link_id', 'tags', 'status'), 'classes': 'collapse'}),
- )
-
-admin.site.register(Link, LinkAdmin) \ No newline at end of file
diff --git a/apps/links/detail_urls.py b/apps/links/detail_urls.py
deleted file mode 100644
index 2b6ec5d..0000000
--- a/apps/links/detail_urls.py
+++ /dev/null
@@ -1,13 +0,0 @@
-from django.conf.urls.defaults import *
-from django.views.generic.simple import redirect_to
-from links.models import Link
-
-
-detail_dict = {
- 'queryset': Link.objects.filter(status__exact=1),
-}
-urlpatterns = patterns('django.views.generic.list_detail',
- (r'^$', redirect_to, {'url': '/links/1/'}),
- (r'^(?P<object_id>\d+)/$', 'object_detail', dict(detail_dict, template_name='details/link.html')),
-)
-
diff --git a/apps/links/models.py b/apps/links/models.py
deleted file mode 100644
index 09acc1c..0000000
--- a/apps/links/models.py
+++ /dev/null
@@ -1,76 +0,0 @@
-import datetime
-
-from django.db import models
-from django.contrib.syndication.feeds import Feed
-from django.contrib.sitemaps import Sitemap
-
-from taggit.managers import TaggableManager
-
-RATINGS = (
- ('1', "1 Star"),
- ('2', "2 Stars"),
- ('3', "3 Stars"),
- ('4', "4 Stars"),
- ('5', "5 Stars"),
-)
-
-DEBUG = 1
-
-class Link(models.Model):
- link_id = models.CharField(max_length=60, blank=True, null=True)
- title = models.CharField(max_length=400)
- url = models.CharField(max_length=400)
- description = models.TextField(blank=True, null=True)
- screen_url = models.CharField(max_length=400, blank=True, null=True)
- rating = models.CharField(max_length=1, choices=RATINGS, null=True)
- pub_date = models.DateTimeField()
- PUB_STATUS = (
- (0, 'Private'),
- (1, 'Public'),
- )
- status = models.IntegerField(choices=PUB_STATUS, default=0)
- tags = TaggableManager(blank=True)
-
- class Meta:
- ordering = ['-pub_date']
-
- def __unicode__(self):
- return self.title
-
- def get_absolute_url(self):
- return self.url
-
- def get_model_name(self):
- return 'link'
-
- def get_previous_published(self):
- return self.get_previous_by_pub_date(status__exact=1)
-
- def get_next_published(self):
- return self.get_next_by_pub_date(status__exact=1)
-
-
- def get_thumbnail_url(self):
- return "http://images.luxagraf.net/magnolia_thumbs/%s" %(self.screen_url)
- def comment_period_open(self):
- return self.enable_comments and datetime.datetime.today() - datetime.timedelta(30) <= self.pub_date
-
-
-class LinkSitemap(Sitemap):
- changefreq = "never"
- priority = 0.4
-
- def items(self):
- return Link.objects.filter(status=1)
-
- def lastmod(self, obj):
- return obj.pub_date
-
-class LatestLinks(Feed):
- title = "Luxagraf: Links"
- link = "http://ma.gnolia.com/people/luxagraf/bookmarks"
- description = "Links to interesting stuff"
- description_template = 'feeds/links_description.html'
-
- def items(self):
- return Link.objects.filter(status__exact=1).order_by('-pub_date')[:10]
diff --git a/apps/links/retriever.py b/apps/links/retriever.py
deleted file mode 100644
index f876405..0000000
--- a/apps/links/retriever.py
+++ /dev/null
@@ -1,111 +0,0 @@
-import datetime
-
-from django.core.exceptions import ObjectDoesNotExist
-from django.template.defaultfilters import striptags
-from django.core.mail import EmailMessage
-from django.conf import settings
-
-
-from utils.strutils import safestr,unquotehtml
-from links.models import Link
-from utils import pinboard
-
-def sync_pinboard_links():
- """
- sync bookmarks from my pinboard account
-
- dependancies: python-pinboard https://github.com/mgan59/python-pinboard/
- """
- p = pinboard.open(settings.PIN_USER, settings.PIN_PASS)
- dupe = False
- links = p.posts(count=30)
- for link in links:
- try:
- #check to see if link exists
- row = Link.objects.get(link_id=safestr(link['hash']))
- except ObjectDoesNotExist:
- l, created = Link.objects.get_or_create(
- title = link['description'],
- link_id = safestr(link['hash']),
- url = safestr(link['href']),
- description = safestr(link['extended']),
- rating = "3",
- pub_date = datetime.datetime.strptime(link['time'], "%Y-%m-%dT%H:%M:%SZ"),
- status = 0
- )
- print l.title
- if created:
- print l.title
- for t in link['tags']:
- l.tags.add(t)
- email_link(l)
-
-'''
-def sync_delicious_links(*args, **kwargs):
- b = delicious.get_all(settings.DELICIOUS_USER, settings.DELICIOUS_PASS)
- dupe = False
- for post in b:
- taglist = []
- try:
- row = Link.objects.get(magnolia_id=safestr(post['hash']))
- # If the row exists already, set the dupe flag
- dupe = True
- except ObjectDoesNotExist:
- #f = copy_file(safestr(post.findtext('screenshot')), safestr(info['id']))
- #fake the image since delicious doesn't offer them
- local_image_url = "%s/%s.jpg" %(safestr(datetime.datetime.today().strftime("%b").lower()), safestr(post['hash']))
- tags = str(post['tag']).split(" ")
- for tag in tags:
- taglist.append(tag)
- for tag in taglist:
- if tag == '2lux':
- status = 1
- break
- else:
- status = 0
- descr = markdown.markdown(unquotehtml(safestr(post['extended'])), safe_mode = False)
- l, created = Link.objects.get_or_create(
- title = post['description'],
- magnolia_id = safestr(post['hash']),
- url = safestr(post['href']),
- description = descr,
- screen_url = local_image_url,
- #fake the rating since delicious doesn't offer such things
- rating = "3",
- pub_date = datetime.datetime.strptime(post['time'], "%Y-%m-%dT%H:%M:%SZ"),
- status = status,
- enable_comments = True,
- tags = ", ".join(t for t in taglist if t != "2lux")
- )
-
- email_link(l)
- if l.status == 1:
- pass
- #post_to_tumblr(l)
- #send_to_deliciousfb(l)
- if(dupe):
- break
-
-
-'''
-
-def email_link(link):
- """
- Sends an imported link to Gmail (never hurts to have backups)
- """
- subject = link.title
- body = "%s\n\n%s\n\n\nvisit site:%s\n" %(link.title, link.description, link.url)
- msg = EmailMessage(subject, striptags(body), 'sng@luxagraf.net', ['luxagraf+links@gmail.com'])
- msg.send()
- msg = EmailMessage(subject, striptags(body), 'sng@luxagraf.net', ['sng+links@luxagraf.net'])
- msg.send()
-
-'''
-def send_to_delicious(link):
- del_tags = ''
- tags = link.tags.split(',')
- for tag in tags:
- del_tags += tag.strip().replace(' ','_')+' '
- delicious.add(settings.DELICIOUS_USER, settings.DELICIOUS_PASS, link.url, link.title, tags = del_tags, extended = striptags(link.description), dt =safestr(link.pub_date), replace="no")
-
-''' \ No newline at end of file
diff --git a/apps/links/tumblr.py b/apps/links/tumblr.py
deleted file mode 100644
index 8c0e286..0000000
--- a/apps/links/tumblr.py
+++ /dev/null
@@ -1,240 +0,0 @@
-#!/usr/bin/python
-# -*- coding: utf-8 -*-
-
-# Copyright 2008 Ryan Cox ( ryan.a.cox@gmail.com ) All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-'''A wrapper library for Tumblr's public web API: http://www.tumblr.com/api'''
-
-__author__ = 'ryan.a.cox@gmail.com'
-__version__ = '0.1'
-
-
-from urllib2 import Request, urlopen, URLError, HTTPError
-from urllib import urlencode, quote
-import base64
-import re
-
-try:
- import simplejson
-except ImportError:
- from django.utils import simplejson
-
-GENERATOR = 'python-tumblr'
-PAGESIZE = 50
-
-
-class TumblrError(Exception):
- ''' General Tumblr error '''
- def __init__(self, msg):
- self.msg = msg
-
- def __str__(self):
- return self.msg
-
-class TumblrAuthError(TumblrError):
- ''' Wraps a 403 result '''
- pass
-
-class TumblrRequestError(TumblrError):
- ''' Wraps a 400 result '''
- pass
-
-class TumblrIterator:
- def __init__(self, name, start, max, type):
- self.name = name
- self.start = start
- self.max = max
- self.type = type
- self.results = None
- self.index = 0
-
- def __iter__(self):
- return self
-
- def next(self):
- if not self.results or (self.index == len(self.results['posts'])):
- self.start += self.index
- self.index = 0
- url = "http://%s.tumblr.com/api/read/json?start=%s&num=%s" % (self.name,self.start, PAGESIZE)
- if self.type:
- url += "&type=" + self.type
- response = urlopen(url)
- page = response.read()
- m = re.match("^.*?({.*}).*$", page,re.DOTALL | re.MULTILINE | re.UNICODE)
- self.results = simplejson.loads(m.group(1))
-
- if (self.index >= self.max) or len(self.results['posts']) == 0:
- raise StopIteration
-
- self.index += 1
- return self.results['posts'][self.index-1]
-
-class Api:
- def __init__(self, name, email=None, password=None ):
- self.name = name
- self.is_authenticated = False
- self.email = email
- self.password = password
-
- def auth_check(self):
- if self.is_authenticated:
- return
- url = 'http://www.tumblr.com/api/write'
- values = {
- 'action': 'authenticate',
- 'generator' : GENERATOR,
- 'email': self.email,
- 'password' : self.password }
-
- data = urlencode(values)
- req = Request(url, data)
- try:
- response = urlopen(req)
- page = response.read()
- self.url = page
- self.is_authenticated = True
- return
- except HTTPError, e:
- if 403 == e.code:
- raise TumblrAuthError(str(e))
- if 400 == e.code:
- raise TumblrRequestError(str(e))
- except Exception, e:
- raise TumblrError(str(e))
-
-
- def write_regular(self, title=None, body=None, **args):
- if title:
- args['title'] = title
- if body:
- args['body'] = body
- args = self._fixnames(args)
- if not 'title' in args and not 'body' in args:
- raise TumblrError("Must supply either body or title argument")
-
- self.auth_check()
- args['type'] = 'regular'
- return self._write(args)
-
- def write_photo(self, source=None, **args):
- if source:
- args['source'] = source
-
- args = self._fixnames(args)
- if 'source' in args and 'data' in args:
- raise TumblrError("Must NOT supply both source and data arguments")
-
- if not 'source' in args and not 'data' in args:
- raise TumblrError("Must supply source or data argument")
-
- self.auth_check()
- args['type'] = 'photo'
- return self._write(args)
-
- def write_quote(self, quote=None, **args):
- if quote:
- args['quote'] = quote
- args = self._fixnames(args)
- if not 'quote' in args:
- raise TumblrError("Must supply quote arguments")
-
- self.auth_check()
- args['type'] = 'quote'
- return self._write(args)
-
- def write_link(self, url=None, **args):
- if url:
- args['url'] = url
- args = self._fixnames(args)
- if not 'url' in args:
- raise TumblrError("Must supply url argument")
-
- self.auth_check()
- args['type'] = 'link'
- return self._write(args)
-
- def write_conversation(self, conversation=None, **args):
- if conversation:
- args['conversation'] = conversation
- args = self._fixnames(args)
- if not 'conversation' in args:
- raise TumblrError("Must supply conversation argument")
-
- self.auth_check()
- args['type'] = 'conversation'
- return self._write(args)
-
- def write_video(self, embed=None, **args):
- if embed:
- args['embed'] = embed
- args = self._fixnames(args)
- if 'embed' in args and 'data' in args:
- raise TumblrError("Must NOT supply both embed and data arguments")
-
- if not 'embed' in args and not 'data' in args:
- raise TumblrError("Must supply embed or data argument")
-
- self.auth_check()
- args['type'] = 'video'
- return self._write(args)
-
- def _fixnames(self, args):
- for key in args:
- if '_' in key:
- value = args[key]
- del args[key]
- args[key.replace('_', '-')] = value
- return args
-
- def _write(self, params, headers=None):
- self.auth_check()
- url = 'http://www.tumblr.com/api/write'
- params['email'] = self.email
- params['password'] = self.password
- params['generator'] = GENERATOR
- data = urlencode(params)
- if headers:
- req = Request(url, data, headers)
- else:
- req = Request(url, data)
- newid = None
- try:
- urlopen(req)
- raise TumblrError("Error writing post")
-
- except HTTPError, e:
- if 201 == e.code:
- newid = e.read()
- return self.read(id=newid)
- raise TumblrError(e.read())
-
- def read(self, id=None, start=0,max=2**31-1,type=None):
- if id:
- url = "http://%s.tumblr.com/api/read/json?id=%s" % (self.name,id)
- print url
- response = urlopen(url)
- page = response.read()
- m = re.match("^.*?({.*}).*$", page,re.DOTALL | re.MULTILINE | re.UNICODE)
- results = simplejson.loads(m.group(1))
- if len(results['posts']) == 0:
- return None
-
- return results['posts'][0]
- else:
- return TumblrIterator(self.name,start,max,type)
-
-if __name__ == "__main__":
- pass
diff --git a/apps/links/urls.py b/apps/links/urls.py
deleted file mode 100644
index 5a16d6e..0000000
--- a/apps/links/urls.py
+++ /dev/null
@@ -1,15 +0,0 @@
-from django.conf.urls.defaults import *
-from django.views.generic import list_detail
-from django.views.generic.simple import redirect_to
-from links.models import Link
-
-photos_paged = {
- 'queryset': Link.objects.filter(status__exact=1).order_by('-pub_date'),
- 'paginate': True,
- 'page_url': '/links/%d/',
-}
-
-urlpatterns = patterns('',
- (r'^(?P<page>\d+)/$', list_detail.object_list, dict(photos_paged, template_name='archives/links.html')),
- (r'^$', redirect_to, {'url': '/links/1/'}),
-)
diff --git a/apps/locations/__init__.py b/apps/locations/__init__.py
deleted file mode 100644
index e69de29..0000000
--- a/apps/locations/__init__.py
+++ /dev/null
diff --git a/apps/locations/admin.py b/apps/locations/admin.py
deleted file mode 100644
index a23ef28..0000000
--- a/apps/locations/admin.py
+++ /dev/null
@@ -1,295 +0,0 @@
-from django.contrib import admin
-from django.contrib.gis.admin import OSMGeoAdmin
-from locations.models import Region,Country,Location,State,Route
-from django.contrib import databrowse
-from django.contrib.gis.maps.google import GoogleMap
-from django.conf import settings
-
-GMAP = GoogleMap(key=settings.GOOGLE_MAPS_API_KEY)
-databrowse.site.register(Region)
-
-class RegionAdmin(OSMGeoAdmin):
- # Standard Django Admin Options
- list_display = ('name','slug')
- prepopulated_fields = {'slug': ('name',)}
- search_fields = ('name',)
- ordering = ('name',)
- save_as = True
- search_fields = ['name',]
- list_select_related = True
- fieldsets = (
- ('Region', {'fields': ('name','slug','pub_date'), 'classes': ('show','extrapretty')}),
- ('Editable Map View', {'fields': ('geometry',), 'classes': ('show', 'wide')}),
- )
- extra_js = [GMAP.api_url + GMAP.key]
- map_template = 'gis/admin/google.html'
- # Default GeoDjango OpenLayers map options
- # Uncomment and modify as desired
- # To learn more about this jargon visit:
- # www.openlayers.org
-
- #default_lon = 0
- #default_lat = 0
- #default_zoom = 4
- #display_wkt = False
- #display_srid = False
- #extra_js = []
- #num_zoom = 18
- #max_zoom = False
- #min_zoom = False
- #units = False
- #max_resolution = False
- #max_extent = False
- #modifiable = True
- #mouse_position = True
- #scale_text = True
- #layerswitcher = True
- scrollable = False
- #admin_media_prefix = settings.ADMIN_MEDIA_PREFIX
- map_width = 700
- map_height = 325
- #map_srid = 4326
- #map_template = 'gis/admin/openlayers.html'
- #openlayers_url = 'http://openlayers.org/api/2.6/OpenLayers.js'
- #wms_url = 'http://labs.metacarta.com/wms/vmap0'
- #wms_layer = 'basic'
- #wms_name = 'OpenLayers WMS'
- #debug = False
- #widget = OpenLayersWidget
-
-# Finally, with these options set now register the model
-# associating the Options with the actual model
-admin.site.register(Region,RegionAdmin)
-
-class CountryAdmin(OSMGeoAdmin):
- """
- # Standard Django Admin Options
- list_display = ('name','slug','region')
- prepopulated_fields = {'slug': ('name',)}
- search_fields = ('name',)
- ordering = ('name',)
- save_as = True
- search_fields = ['name',]
- list_select_related = True
- fieldsets = (
- ('Country', {'fields': ('name','slug','abbr','region','pub_date'), 'classes': ('show','extrapretty')}),
- ('Editable Map View', {'fields': ('geometry',), 'classes': ('show', 'wide')}),
- )
- """
-
- # Standard Django Admin Options
- list_display = ('name','pop2005','region','subregion',)
- search_fields = ('name',)
- ordering = ('name',)
- list_filter = ('visited','region','subregion',)
- save_as = True
- search_fields = ['name','iso2','iso3','subregion','region']
- list_select_related = True
- fieldsets = (
- ('Country Attributes', {'fields': (('name','pop2005','slug','zoom_level','visited')), 'classes': ('show','extrapretty')}),
- ('Country Codes', {'fields': ('region','subregion','iso2','iso3','un',), 'classes': ('collapse',)}),
- ('Area and Coordinates', {'fields': ('area','lat','lon',), 'classes': ('collapse', 'wide')}),
- ('Editable Map View', {'fields': ('geometry',), 'classes': ('show', 'wide')}),
- )
-
- extra_js = [GMAP.api_url + GMAP.key]
- map_template = 'gis/admin/google.html'
- # Default GeoDjango OpenLayers map options
- # Uncomment and modify as desired
- # To learn more about this jargon visit:
- # www.openlayers.org
-
- #default_lon = 0
- #default_lat = 0
- #default_zoom = 4
- #display_wkt = False
- #display_srid = False
- #extra_js = []
- #num_zoom = 18
- #max_zoom = False
- #min_zoom = False
- #units = False
- #max_resolution = False
- #max_extent = False
- #modifiable = True
- #mouse_position = True
- #scale_text = True
- #layerswitcher = True
- scrollable = False
- #admin_media_prefix = settings.ADMIN_MEDIA_PREFIX
- map_width = 700
- map_height = 325
- #map_srid = 4326
- #map_template = 'gis/admin/openlayers.html'
- #openlayers_url = 'http://openlayers.org/api/2.6/OpenLayers.js'
- #wms_url = 'http://labs.metacarta.com/wms/vmap0'
- #wms_layer = 'basic'
- #wms_name = 'OpenLayers WMS'
- #debug = False
- #widget = OpenLayersWidget
-
-# Finally, with these options set now register the model
-# associating the Options with the actual model
-admin.site.register(Country,CountryAdmin)
-
-
-
-class StateAdmin(OSMGeoAdmin):
- # Standard Django Admin Options
- list_display = ('name','code','slug','country')
- prepopulated_fields = {'slug': ('name',)}
- search_fields = ('name','country')
- ordering = ('name',)
- save_as = True
- search_fields = ['name',]
- list_select_related = True
- fieldsets = (
- ('Location', {'fields': ('name','slug','code','pub_date','country'), 'classes': ('show','extrapretty')}),
- ('Editable Map View', {'fields': ('geometry',), 'classes': ('show', 'wide')}),
- )
- extra_js = [GMAP.api_url + GMAP.key]
- map_template = 'gis/admin/google.html'
- # Default GeoDjango OpenLayers map options
- # Uncomment and modify as desired
- # To learn more about this jargon visit:
- # www.openlayers.org
-
- #default_lon = 0
- #default_lat = 0
- #default_zoom = 4
- #display_wkt = False
- #display_srid = False
- #extra_js = []
- #num_zoom = 18
- #max_zoom = False
- #min_zoom = False
- #units = False
- #max_resolution = False
- #max_extent = False
- #modifiable = True
- #mouse_position = True
- #scale_text = True
- #layerswitcher = True
- scrollable = False
- #admin_media_prefix = settings.ADMIN_MEDIA_PREFIX
- map_width = 700
- map_height = 325
- #map_srid = 4326
- #map_template = 'gis/admin/openlayers.html'
- #openlayers_url = 'http://openlayers.org/api/2.6/OpenLayers.js'
- #wms_url = 'http://labs.metacarta.com/wms/vmap0'
- #wms_layer = 'basic'
- #wms_name = 'OpenLayers WMS'
- #debug = False
- #widget = OpenLayersWidget
-
-# Finally, with these options set now register the model
-# associating the Options with the actual model
-admin.site.register(State,StateAdmin)
-
-class LocationAdmin(OSMGeoAdmin):
- # Standard Django Admin Options
- list_display = ('name','slug','state')
- prepopulated_fields = {'slug': ('name',)}
- search_fields = ('name','state')
- ordering = ('name',)
- save_as = True
- search_fields = ['name',]
- list_select_related = True
- fieldsets = (
- ('Location', {'fields': ('name','slug','pub_date','state'), 'classes': ('show','extrapretty')}),
- ('Editable Map View', {'fields': ('geometry',), 'classes': ('show', 'wide')}),
- )
- extra_js = [GMAP.api_url + GMAP.key]
- map_template = 'gis/admin/google.html'
- # Default GeoDjango OpenLayers map options
- # Uncomment and modify as desired
- # To learn more about this jargon visit:
- # www.openlayers.org
-
- #default_lon = 0
- #default_lat = 0
- #default_zoom = 4
- #display_wkt = False
- #display_srid = False
- #extra_js = []
- #num_zoom = 18
- #max_zoom = False
- #min_zoom = False
- #units = False
- #max_resolution = False
- #max_extent = False
- #modifiable = True
- #mouse_position = True
- #scale_text = True
- #layerswitcher = True
- scrollable = False
- #admin_media_prefix = settings.ADMIN_MEDIA_PREFIX
- map_width = 700
- map_height = 325
- #map_srid = 4326
- #map_template = 'gis/admin/openlayers.html'
- #openlayers_url = 'http://openlayers.org/api/2.6/OpenLayers.js'
- #wms_url = 'http://labs.metacarta.com/wms/vmap0'
- #wms_layer = 'basic'
- #wms_name = 'OpenLayers WMS'
- #debug = False
- #widget = OpenLayersWidget
-
-# Finally, with these options set now register the model
-# associating the Options with the actual model
-admin.site.register(Location,LocationAdmin)
-
-class RouteAdmin(OSMGeoAdmin):
- # Standard Django Admin Options
- list_display = ('name','slug',)
- prepopulated_fields = {'slug': ('name',)}
- search_fields = ('name',)
- ordering = ('name',)
- save_as = True
- search_fields = ['name',]
- list_select_related = True
- fieldsets = (
- ('Location', {'fields': ('name','slug','pub_date','template_var_name','zoom'), 'classes': ('show','extrapretty')}),
- ('Editable Map View', {'fields': ('geometry',), 'classes': ('show', 'wide')}),
- )
- extra_js = [GMAP.api_url + GMAP.key]
- map_template = 'gis/admin/google.html'
- # Default GeoDjango OpenLayers map options
- # Uncomment and modify as desired
- # To learn more about this jargon visit:
- # www.openlayers.org
-
- #default_lon = 0
- #default_lat = 0
- #default_zoom = 4
- #display_wkt = False
- #display_srid = False
- #extra_js = []
- #num_zoom = 18
- #max_zoom = False
- #min_zoom = False
- #units = False
- #max_resolution = False
- #max_extent = False
- #modifiable = True
- #mouse_position = True
- #scale_text = True
- #layerswitcher = True
- scrollable = False
- #admin_media_prefix = settings.ADMIN_MEDIA_PREFIX
- map_width = 700
- map_height = 325
- #map_srid = 4326
- #map_template = 'gis/admin/openlayers.html'
- #openlayers_url = 'http://openlayers.org/api/2.6/OpenLayers.js'
- #wms_url = 'http://labs.metacarta.com/wms/vmap0'
- #wms_layer = 'basic'
- #wms_name = 'OpenLayers WMS'
- #debug = False
- #widget = OpenLayersWidget
-
-# Finally, with these options set now register the model
-# associating the Options with the actual model
-admin.site.register(Route,RouteAdmin)
-
diff --git a/apps/locations/models.py b/apps/locations/models.py
deleted file mode 100644
index e088697..0000000
--- a/apps/locations/models.py
+++ /dev/null
@@ -1,190 +0,0 @@
-# -*- coding: utf-8 -*-
-# models.py
-
-# All standard Django fields as well as GeoDjango geometry fields and the GeoManager() can be
-# imported from django.contrib.gis.db after adding django.contrib.gis to INSTALLED_APPS
-from django.contrib.gis.db import models
-from django.contrib.sitemaps import Sitemap
-# Used to display html 'help text' links within Admin App
-from django.utils.safestring import mark_safe
-
-class Region(models.Model):
- name = models.CharField(max_length=50, )
- slug = models.SlugField()
- pub_date = models.DateTimeField('Date published',null=True)
- # GeoDjango specific Polygon Field and GeoManager
- geometry = models.MultiPolygonField(srid=4326, null=True)
- lon = models.FloatField('Longitude',help_text="Longitude of centerpoint",null=True)
- lat = models.FloatField('Latitude',help_text="Latitude of centerpoint",null=True)
- zoom_level = models.CharField(max_length=2,null=True)
- # GeoManager, a subclass that adds a rich set of geospatial queryset methods
- objects = models.GeoManager()
-
- def get_absolute_url(self):
- return "/locations/region/%s/" % (self.slug)
-
- def __unicode__(self): return self.name
-
-
-# imported from django.contrib.gis.db
-from django.contrib.gis.db import models
-
-# Used to display html 'help text' links within Admin App
-from django.utils.safestring import mark_safe
-
-class Country(models.Model):
- """
-
- A geographic model based on the v3 of the simplified world borders multipolygon shapefile
- from http://thematicmapping.org/downloads/world_borders.php.
-
- Field names, Django types, and max_lengths were autogenerated using the ogrinspect utility with hand
- edits to add alternative field names and help_text.
-
- Imported using LayerMapping (requires GDAL) called within the load_data.py script provided
- within this sample project.
-
- All fields match the source dataset, an ESRI format shapefile made up of several related files:
- .shp - holds the vector data that is to be stored in the MultiPolygonField field named'geometry'.
- .shx - spatial index file for geometries stored in the .shp.
- .dbf - database file for holding attribute data (can be opened in excel and open office).
- .prj - contains the spatial reference information for the geometries stored in the .shp
-
-
- """
-
- # Regular Django fields corresponding to the attributes in the
- # world borders shapefile
- name = models.CharField(max_length=50)
- area = models.IntegerField(help_text="Area of Country in SQ meters")
- pop2005 = models.IntegerField('Population 2005')
- fips = models.CharField('FIPS Code', max_length=2, help_text=mark_safe('<a href="http://www.census.gov/geo/www/fips/fips.html">Federal Information Processing Standard Code</a>'))
- iso2 = models.CharField('2 Digit ISO', max_length=2, help_text=mark_safe('<a href="http://www.iso.org/">International Organization for Standardization</a>' ))
- iso3 = models.CharField('3 Digit ISO', max_length=3,help_text=mark_safe('<a href="http://www.iso.org/">International Organization for Standardization</a>' ))
- un = models.IntegerField('United Nations Code')
- REGION_CODES = (
- (0, 'MISC'),
- (2, 'Africa'),
- (9, 'Oceania'),
- (19, 'Americas'),
- (142, 'Asia'),
- (150, 'Europe'),
- )
- SUBREGION_CODES = (
- (0, 'MISC'),
- (5, 'South America'),
- (11, 'Western Africa'),
- (13, 'Central America'),
- (14, 'Eastern Africa'),
- (15, 'Northern Africa'),
- (17, 'Middle Africa'),
- (18, 'Southern Africa'),
- (21, 'North America'),
- (29, 'Caribbean'),
- (30, 'Eastern Asia'),
- (34, 'Southern Asia'),
- (35, 'Southeast Asia'),
- (39, 'Southern Europe'),
- (53, 'Australia and New Zealand'),
- (54, 'Melanesia'),
- (57, 'Micronesia'),
- (61, 'Polynesia'),
- (143, 'Central Asia'),
- (145, 'Western Asia'),
- (151, 'Eastern Europe'),
- (154, 'Northern Europe'),
- (155, 'Western Europe'),
- )
- region = models.IntegerField('Region Code',choices=REGION_CODES)
- subregion = models.IntegerField('Sub-Region Code',choices=SUBREGION_CODES)
- lon = models.FloatField('Longitude',help_text="Longitude of centerpoint")
- lat = models.FloatField('Latitude',help_text="Latitude of centerpoint")
- zoom_level = models.CharField(max_length=2,null=True)
- slug = models.SlugField(null=True)
- visited = models.BooleanField(default=False)
- lux_region = models.ForeignKey(Region, null=True)
- pub_date = models.DateTimeField('Date published',null=True)
- # GeoDjango-specific: a geometry field (MultiPolygonField), and
- # overriding the default manager with a GeoManager instance.
- geometry = models.MultiPolygonField('Country Border',srid=4326)
- objects = models.GeoManager()
-
-
- # Returns the string representation of the model.
- def __unicode__(self):
- return self.name
-
- class Meta:
- ordering = ['name']
- verbose_name_plural = 'Countries'
-
- def get_absolute_url(self):
- return "/locations/%s/" % (self.slug)
-
-
-class State(models.Model):
- name = models.CharField(max_length=250, blank=True, null=True,)
- country = models.ForeignKey(Country)
- slug = models.SlugField()
- code = models.CharField(max_length=2, null=True, blank=True)
- pub_date = models.DateTimeField('Date published',null=True)
- geometry = models.MultiPolygonField(srid=4326,null=True)
- objects = models.GeoManager()
-
- class Meta:
- ordering = ['name']
-
- class Admin:
- pass
-
- def __unicode__(self):
- return "%s" %(self.name)
-
- def get_absolute_url(self):
- return "/locations/%s/%s/" % (self.country.slug, self.slug)
-
-class Location(models.Model):
- state = models.ForeignKey(State)
- name = models.CharField(max_length=50, )
- slug = models.SlugField()
- pub_date = models.DateTimeField('Date published',null=True)
- # GeoDjango specific Polygon Field and GeoManager
- geometry = models.MultiPolygonField(srid=4326)
- # GeoManager, a subclass that adds a rich set of geospatial queryset methods
- objects = models.GeoManager()
-
- def get_absolute_url(self):
- return "/locations/%s/%s/%s/" % (self.state.country.slug, self.state.slug, self.slug)
-
-
- def __unicode__(self): return self.name
-
-class Route(models.Model):
- name = models.CharField(max_length=200)
- slug = models.SlugField()
- zoom = models.CharField(max_length=2, null=True)
- template_var_name = models.CharField(max_length=10, null=True)
- pub_date = models.DateTimeField('Date published',null=True)
- # GeoDjango specific Polygon Field and GeoManager
- geometry = models.MultiPointField(srid=4326)
- # GeoManager, a subclass that adds a rich set of geospatial queryset methods
- objects = models.GeoManager()
-
- def get_absolute_url(self):
- return "/locations/%s/%s/%s/" % (self.slug)
-
-
- def __unicode__(self): return self.name
-
-
-
-class WritingbyLocationSitemap(Sitemap):
- changefreq = "weekly"
- priority = 0.6
-
- def location():
- return '/writing/%s/1/' %(self.slug)
-
- def items(self):
- return Location.objects.all()
-
diff --git a/apps/locations/urls.py b/apps/locations/urls.py
deleted file mode 100644
index c49e684..0000000
--- a/apps/locations/urls.py
+++ /dev/null
@@ -1,7 +0,0 @@
-from django.conf.urls.defaults import *
-from django.views.generic.simple import redirect_to,direct_to_template
-
-urlpatterns = patterns('',
- (r'data/(?P<id>\d+)/$', 'locations.views.data_json'),
- (r'^$', direct_to_template, {'template': 'archives/map.html'}),
-)
diff --git a/apps/locations/views.py b/apps/locations/views.py
deleted file mode 100644
index f360429..0000000
--- a/apps/locations/views.py
+++ /dev/null
@@ -1,25 +0,0 @@
-from django.shortcuts import render_to_response,get_object_or_404
-from django.template import RequestContext
-
-from blog.models import Entry
-from locations.models import Location, Country, Region, Route
-
-def list_view(request):
- context = {
- 'object_list' : Entry.objects.filter(status__exact=1),
- 'country_list' : Country.objects.filter(visited=True).exclude(name='default'),
- 'region_list' : Region.objects.all()
- }
- return render_to_response('archives/map.html', context, context_instance=RequestContext(request))
-
-from projects.shortcuts import render_to_geojson
-
-def data_json(request, id):
- qs = Route.objects.filter(pk=id)
- return render_to_geojson(
- qs,
- included_fields=['id',],
- geom_attribute='geometry',
- mimetype = 'application/json',
- pretty_print=True
- ) \ No newline at end of file
diff --git a/apps/photos/__init__.py b/apps/photos/__init__.py
deleted file mode 100644
index e69de29..0000000
--- a/apps/photos/__init__.py
+++ /dev/null
diff --git a/apps/photos/admin.py b/apps/photos/admin.py
deleted file mode 100644
index 29f5dbf..0000000
--- a/apps/photos/admin.py
+++ /dev/null
@@ -1,67 +0,0 @@
-from django.contrib import admin
-from django.contrib.gis.admin import OSMGeoAdmin
-from django.contrib.gis.maps.google import GoogleMap
-from django.conf import settings
-
-from photos.models import Photo,PhotoGallery
-
-GMAP = GoogleMap(key=settings.GOOGLE_MAPS_API_KEY)
-
-class PhotoAdmin(OSMGeoAdmin):
- list_display = ('title','admin_thumbnail', 'flickr_id', 'pub_date',)
- list_filter = ('pub_date',)
- search_fields = ['title', 'description']
- fieldsets = (
- (None, {'fields': (('title', 'description'),'pub_date', 'tags',('lat','lon'))}),
- ('Exif Data', {'fields': ('exif_aperture','exif_exposure','exif_iso','exif_focal_length','exif_lens','exif_date','exif_make','exif_model'), 'classes': ('collapse')}),
- ('Flickr Data', {'fields': ('flickr_id','flickr_owner','flickr_farm','flickr_server','flickr_secret','flickr_originalsecret'), 'classes': ('collapse')}),
- )
- extra_js = [GMAP.api_url + GMAP.key]
- map_template = 'gis/admin/google.html'
- # Default GeoDjango OpenLayers map options
- # Uncomment and modify as desired
- # To learn more about this jargon visit:
- # www.openlayers.org
-
- #default_lon = 0
- #default_lat = 0
- #default_zoom = 4
- #display_wkt = False
- #display_srid = False
- #extra_js = []
- #num_zoom = 18
- #max_zoom = False
- #min_zoom = False
- #units = False
- #max_resolution = False
- #max_extent = False
- #modifiable = True
- #mouse_position = True
- #scale_text = True
- #layerswitcher = True
- scrollable = False
- #admin_media_prefix = settings.ADMIN_MEDIA_PREFIX
- map_width = 700
- map_height = 325
- #map_srid = 4326
- #map_template = 'gis/admin/openlayers.html'
- #openlayers_url = 'http://openlayers.org/api/2.6/OpenLayers.js'
- #wms_url = 'http://labs.metacarta.com/wms/vmap0'
- #wms_layer = 'basic'
- #wms_name = 'OpenLayers WMS'
- #debug = False
- #widget = OpenLayersWidget
-
-admin.site.register(Photo, PhotoAdmin)
-
-
-class PhotoGalleryAdmin(OSMGeoAdmin):
- list_display = ('set_title','region','location','pub_date')
- list_filter = ('region','location')
- fieldsets = (
- (None, {'fields': (('set_id','set_title', 'set_desc'),'set_slug','primary','location','region','photos','pub_date')}),
- )
-
-
-
-admin.site.register(PhotoGallery, PhotoGalleryAdmin) \ No newline at end of file
diff --git a/apps/photos/detail_urls.py b/apps/photos/detail_urls.py
deleted file mode 100644
index 9ff9b84..0000000
--- a/apps/photos/detail_urls.py
+++ /dev/null
@@ -1,10 +0,0 @@
-from django.conf.urls.defaults import *
-from photos.models import Photo
-
-detail_dict = {
- 'queryset': Photo.objects.all(),
-}
-
-urlpatterns = patterns('django.views.generic.list_detail',
- (r'^(?P<object_id>\d+)/$', 'object_detail', dict(detail_dict, template_name='details/photo.html')),
-)
diff --git a/apps/photos/models.py b/apps/photos/models.py
deleted file mode 100644
index d5f4d51..0000000
--- a/apps/photos/models.py
+++ /dev/null
@@ -1,201 +0,0 @@
-import datetime
-import Image
-from django.contrib.gis.db import models
-from django.contrib.syndication.feeds import Feed
-from django.contrib.sitemaps import Sitemap
-from django.utils.encoding import force_unicode
-from django.conf import settings
-
-
-from taggit.managers import TaggableManager
-
-from locations.models import Location,Region
-
-class Photo(models.Model):
- description = models.TextField(blank=True, null=True)
- title = models.CharField(blank=True, max_length=300)
- pub_date = models.DateTimeField()
- tags = TaggableManager(blank=True)
- exif_aperture = models.CharField(max_length=50, blank=True, null=True)
- exif_make = models.CharField(max_length=50, blank=True, null=True)
- exif_model = models.CharField(max_length=50, blank=True, null=True)
- exif_exposure = models.CharField(max_length=50, blank=True, null=True)
- exif_iso = models.CharField(max_length=50, blank=True, null=True)
- exif_focal_length = models.CharField(max_length=50, blank=True, null=True)
- exif_lens = models.CharField(max_length=50, blank=True, null=True)
- exif_date = models.DateTimeField()
- """Flickr Specific Stuff"""
- flickr_id = models.CharField(max_length=300) #varchar since Flickr ids are larger than than integerfield can handle and BigIntegerField gets weird in Postgres.
- flickr_owner = models.CharField(max_length=20)
- flickr_server = models.IntegerField()
- flickr_farm = models.IntegerField()
- flickr_secret = models.CharField(max_length=50)
- flickr_originalsecret = models.CharField(max_length=50)
- lon = models.FloatField('Longitude',help_text="Longitude of centerpoint",null=True)
- lat = models.FloatField('Latitude',help_text="Latitude of centerpoint",null=True)
- location = models.ForeignKey(Location, null=True)
- region = models.ForeignKey(Region, null=True)
- slideshowimage_width = models.CharField(max_length=4, blank=True, null=True)
- slideshowimage_height = models.CharField(max_length=4, blank=True, null=True)
- slideshowimage_margintop = models.CharField(max_length=4, blank=True, null=True)
- slideshowimage_marginleft = models.CharField(max_length=4, blank=True, null=True)
-
-
-
- class Meta:
- ordering = ('-pub_date',)
-
-
- def admin_thumbnail(self):
- return force_unicode('<a href="%s"><img src="%s"></a>' % \
- (self.get_absolute_url(), self.get_small_square_url()))
- admin_thumbnail.allow_tags = True
- admin_thumbnail.short_description = 'Thumbnail'
-
- def get_local_medium_url(self):
- return '%sflickr/med/%s/%s.jpg' %(settings.IMAGES_URL,self.pub_date.strftime("%Y"),self.flickr_id)
-
- def get_local_orig_url(self):
- return '%sflickr/full/%s/%s.jpg' %(settings.IMAGES_URL,self.pub_date.strftime("%Y"),self.flickr_id)
-
- def get_local_slideshow_url(self):
- return '%sslideshow/%s/%s.jpg' %(settings.IMAGES_URL,self.pub_date.strftime("%Y"),self.flickr_id)
- def __unicode__(self):
- return self.title
-
- def get_absolute_url(self):
- return "/photo/%s/" % (self.id)
-
- def get_model_name(self):
- return 'photo'
-
- def get_small_square_url(self):
- return self.get_pic_url(size="small_square")
-
- def get_large_url(self):
- return self.get_pic_url(size="large")
-
- def get_small_url(self):
- return self.get_pic_url(size="small")
-
- def get_medium_url(self):
- return self.get_pic_url(size="medium")
-
- def get_original_url(self):
- #return self.get_pic_url(size="original")
- return "http://farm%s.static.flickr.com/%s/%s_%s_o.jpg" % (self.flickr_farm, self.flickr_server, self.flickr_id, self.flickr_originalsecret)
-
- @property
- def get_height(self):
- im = Image.open('%sslideshow/%s/%s.jpg' %(settings.IMAGES_ROOT,self.pub_date.strftime("%Y"),self.flickr_id))
- xsize, ysize = im.size
- return ysize
- @property
- def get_width(self):
- im = Image.open('%sslideshow/%s/%s.jpg' %(settings.IMAGES_ROOT,self.pub_date.strftime("%Y"),self.flickr_id))
- xsize, ysize = im.size
- cal = xsize-120
- return xsize
- @property
- def get_margin_top(self):
- im = Image.open('%sslideshow/%s/%s.jpg' %(settings.IMAGES_ROOT,self.pub_date.strftime("%Y"),self.flickr_id))
- xsize, ysize = im.size
- mtop = 340-(ysize/2)
- return mtop
-
- @property
- def get_margin_left(self):
- im = Image.open('%sslideshow/%s/%s.jpg' %(settings.IMAGES_ROOT,self.pub_date.strftime("%Y"),self.flickr_id))
- xsize, ysize = im.size
- mtop = 500-(xsize/2)
- return mtop
-
- @property
- def flickr_link(self):
- return '%s%s/' %('http://www.flickr.com/photos/luxagraf/', self.flickr_id)
-
- @property
- def is_portait(self):
- if int(self.slideshowimage_height) > int(self.slideshowimage_width):
- return True
- else:
- return False
- def get_pic_url(self, size='small'):
- # small_square=75x75
- # thumb=100 on longest side
- # small=240 on longest side
- # medium=500 on longest side
- # large=1024 on longest side
- # original=duh
-
- base_url = "http://static.flickr.com"
- size_char='s' # default to small_square
-
- if size == 'small_square':
- size_char='_s'
- elif size == 'thumb':
- size_char='_t'
- elif size == 'small':
- size_char='_m'
- elif size == 'medium':
- size_char=''
- elif size == 'large':
- size_char='_b'
- elif size == 'original':
- size_char='_o'
-
- return "http://farm%s.static.flickr.com/%s/%s_%s%s.jpg" % (self.flickr_farm, self.flickr_server, self.flickr_id, self.flickr_secret, size_char)
-
- def get_tumble_image(self):
- return "%s/crops/%s/%s.jpg" %(settings.IMAGES_URL, self.pub_date.strftime("%Y/%b").lower(), self.id)
-
-
- def get_previous_published(self):
- return self.get_previous_by_pub_date()
-
- def get_next_published(self):
- return self.get_next_by_pub_date()
-
- def comment_period_open(self):
- return self.enable_comments and datetime.datetime.today() - datetime.timedelta(30) <= self.pub_date
-
- def save(self, *args, **kwargs):
- super(Photo, self).save()
-
-class PhotoGallery(models.Model):
- set_id = models.CharField(blank=True, max_length=300)
- set_title = models.CharField(blank=True, max_length=300)
- set_desc = models.TextField(blank=True, null=True)
- set_slug = models.CharField(blank=True, max_length=300)
- primary = models.CharField(blank=True, max_length=300)
- photos = models.ManyToManyField(Photo)
- location = models.ForeignKey(Location, null=True)
- region = models.ForeignKey(Region, null=True)
- pub_date = models.DateTimeField(null=True)
-
- class Meta:
- ordering = ('-pub_date','id')
- verbose_name_plural = 'Photo Galleries'
- get_latest_by = 'pub_date'
-
-
- def __unicode__(self):
- return self.set_title
-
- def get_main_image(self):
- return "%sgallery_thumbs/%s.jpg" % (settings.IMAGES_URL, self.id)
-
- def get_absolute_url(self):
- return "/photos/galleries/%s/" % (self.set_slug)
-
-
-class PhotoGallerySitemap(Sitemap):
- changefreq = "never"
- priority = 0.7
-
- def items(self):
- return PhotoGallery.objects.all()
-
- def lastmod(self, obj):
- return obj.pub_date
-
diff --git a/apps/photos/retriever.py b/apps/photos/retriever.py
deleted file mode 100644
index 2a98d09..0000000
--- a/apps/photos/retriever.py
+++ /dev/null
@@ -1,512 +0,0 @@
-from __future__ import division
-import datetime
-import os
-import cStringIO # *much* faster than StringIO
-import urllib
-
-
-from django.contrib.contenttypes.models import ContentType
-from django.template.defaultfilters import slugify
-from django.core.exceptions import ObjectDoesNotExist
-from django.utils.encoding import force_unicode,smart_unicode
-from django.conf import settings
-
-# Required PIL classes may or may not be available from the root namespace
-# depending on the installation
-try:
- import Image
- import ImageFile
- import ImageFilter
- import ImageEnhance
-except ImportError:
- try:
- from PIL import Image
- from PIL import ImageFile
- from PIL import ImageFilter
- from PIL import ImageEnhance
- except ImportError:
- raise ImportError("Could not import the Python Imaging Library.")
-
-
-from utils.strutils import safestr
-from photos.models import Photo,PhotoGallery
-
-
-# Flickr Sync stuffs
-API_KEY = settings.FLICKR_API_KEY
-from utils.APIClients import FlickrClient
-
-EXIF_PARAMS = {"Aperture":'f/2.8',"Make":'Apple',"Model":'iPhone',"Exposure":'',"ISO Speed":'',"Focal Length":'',"Shutter Speed":'',"Lens":'','Date and Time (Original)':'2008:07:03 22:44:25'}
-
-def sync_flickr_photos(*args, **kwargs):
- cur_page = 1 # Start on the first page of the stream
- paginate_by = 100 # Get 100 photos at a time
- dupe = False # Set our dupe flag for the following loop
- BASE_PATH = 'http://flickr.com/services/rest/'
- client = FlickrClient(BASE_PATH, API_KEY)
- data = client.flickr_people_getPublicPhotos(user_id=settings.FLICKR_USER_ID, page=cur_page, per_page=paginate_by,extras="date_upload,date_taken,geo")
- #photos.photos.photo.reverse()
- for post in data.findall('photos/photo'):
- info = dict((k, smart_unicode(post.get(k))) for k in post.keys())
- try:
- row = Photo.objects.get(flickr_id=info['id'], flickr_secret=info['secret'])
- # If the row exists already, set the dupe flag
- dupe = True
- print 'already have '+info['id']+' moving on'
- except ObjectDoesNotExist:
- #for debugging:
- print info['title']
- taglist = []
- location, region = get_geo(float(info['latitude']),float(info['longitude']))
- details = client.flickr_photos_getInfo(user_id=settings.FLICKR_USER_ID, photo_id=force_unicode(info['id']))
- for t in details.findall('photo/tags/tag'):
- tag = dict((k, smart_unicode(t.get(k))) for k in t.keys())
- taglist.append(tag['raw'])
- exif = exif_handler(client.flickr_photos_getExif(user_id=API_KEY, photo_id=safestr(info['id'])))
-
- photo, created = Photo.objects.get_or_create(
- title = info['title'],
- flickr_id = info['id'],
- flickr_owner = info['owner'],
- flickr_server = info['server'],
- flickr_secret = info['secret'],
- flickr_originalsecret = force_unicode(details[0].attrib['originalsecret']),
- flickr_farm = info['farm'],
- pub_date = flickr_datetime_to_datetime(info['datetaken']),
- description = force_unicode(details[0].findtext('description')),
- exif_aperture = exif['Aperture'],
- exif_make = exif['Make'],
- exif_model = exif['Model'],
- exif_exposure = exif['Exposure'],
- exif_iso = exif['ISO Speed'],
- exif_lens = exif['Lens'],
- exif_focal_length = exif['Focal Length'],
- exif_date = flickr_datetime_to_datetime(exif["Date and Time (Original)"].replace(':', '-', 2)),
- lat = float(info['latitude']),
- lon = float(info['longitude']),
- region = region,
- location = location,
- )
- if created:
- for t in taglist:
- photo.tags.add(t)
- #print info['title'], region, location
- photo.save()
- make_local_copies(photo)
- slideshow_image(photo)
-
-
-def exif_handler(data):
- converted = {}
- try:
- for t in data.findall('photo/exif'):
- e = dict((k, smart_unicode(t.get(k))) for k in t.keys())
- if safestr(e['label']) == "Aperture":
- if not converted.has_key("Aperture"):
- converted["Aperture"] = safestr(t.findtext('clean'))
- else:
- if safestr(e['tag']) != 'Exposure':
- if safestr(e['tag']) == 'ExposureTime':
- converted[safestr(e['label'])] = safestr(t.findtext('clean'))
- else:
- converted[safestr(e['label'])] = safestr(t.findtext('raw'))
- except:
- pass
- for k,v in EXIF_PARAMS.items():
- if not converted.has_key(k):
- converted[k] = v
- return converted
-
-
-def flickr_datetime_to_datetime(fdt):
- from datetime import datetime
- from time import strptime
- date_parts = strptime(fdt, '%Y-%m-%d %H:%M:%S')
- return datetime(*date_parts[0:6])
-
-def get_geo(lat,lon):
- from locations.models import Location, Region
- from django.contrib.gis.geos import Point
- pnt_wkt = Point(lon, lat)
- try:
- location = Location.objects.get(geometry__contains=pnt_wkt)
- except Location.DoesNotExist:
- location = None
- try:
- region = Region.objects.get(geometry__contains=pnt_wkt)
- except Region.DoesNotExist:
- region = None
- return location, region
-
-
-ImageFile.MAXBLOCK = 1000000
-
-def slideshow_image(photo):
- slide_dir = settings.IMAGES_ROOT + '/slideshow/'+ photo.pub_date.strftime("%Y")
- if not os.path.isdir(slide_dir):
- os.makedirs(slide_dir)
- med = photo.get_original_url()
- fname = urllib.urlopen(med)
- im = cStringIO.StringIO(fname.read()) # constructs a StringIO holding the image
- img = Image.open(im)
- cur_width, cur_height = img.size
- #if image landscape
- if cur_width > cur_height:
- new_width = 1000
- #check to make sure we aren't upsizing
- if cur_width > new_width:
- ratio = float(new_width)/cur_width
- x = (cur_width * ratio)
- y = (cur_height * ratio)
- resized = img.resize((int(x), int(y)), Image.ANTIALIAS)
- resized_filename = '%s/%s.jpg' %(slide_dir, photo.flickr_id)
- resized.save(resized_filename, 'JPEG', quality=95, optimize=True)
- else:
- filename = '%s/%s.jpg' %(slide_dir, photo.flickr_id)
- img.save(filename)
- else:
- #image portrait
- new_height = 800
- #check to make sure we aren't upsizing
- if cur_height > new_height:
- ratio = float(new_height)/cur_height
- x = (cur_width * ratio)
- y = (cur_height * ratio)
- resized = img.resize((int(x), int(y)), Image.ANTIALIAS)
- resized_filename = '%s/%s.jpg' %(slide_dir, photo.flickr_id)
- resized.save(resized_filename, 'JPEG', quality=95, optimize=True)
- else:
- filename = '%s/%s.jpg' %(slide_dir, photo.flickr_id)
- img.save(filename)
- photo.slideshowimage_width = photo.get_width
- photo.slideshowimage_height = photo.get_height
- photo.slideshowimage_margintop = photo.get_margin_top
- photo.slideshowimage_marginleft = photo.get_margin_left
- photo.save()
-
-def make_local_copies(photo):
- orig_dir = settings.IMAGES_ROOT + '/flickr/full/'+ photo.pub_date.strftime("%Y")
- if not os.path.isdir(orig_dir):
- os.makedirs(orig_dir)
- full = photo.get_original_url()
- fname = urllib.urlopen(full)
- im = cStringIO.StringIO(fname.read()) # constructs a StringIO holding the image
- img = Image.open(im)
- local_full = '%s/%s.jpg' %(orig_dir, photo.flickr_id)
- img.save(local_full)
- #save large size
- large_dir = settings.IMAGES_ROOT + '/flickr/large/'+ photo.pub_date.strftime("%Y")
- if not os.path.isdir(large_dir):
- os.makedirs(large_dir)
- large = photo.get_large_url()
- fname = urllib.urlopen(large)
- im = cStringIO.StringIO(fname.read()) # constructs a StringIO holding the image
- img = Image.open(im)
- local_large = '%s/%s.jpg' %(large_dir, photo.flickr_id)
- if img.format == 'JPEG':
- img.save(local_large)
- #save medium size
- med_dir = settings.IMAGES_ROOT + '/flickr/med/'+ photo.pub_date.strftime("%Y")
- if not os.path.isdir(med_dir):
- os.makedirs(med_dir)
- med = photo.get_medium_url()
- fname = urllib.urlopen(med)
- im = cStringIO.StringIO(fname.read()) # constructs a StringIO holding the image
- img = Image.open(im)
- local_med = '%s/%s.jpg' %(med_dir, photo.flickr_id)
- img.save(local_med)
-
-
-
-def make_gallery_thumb(photo,set):
- crop_dir = settings.IMAGES_ROOT + '/gallery_thumbs/'
- if not os.path.isdir(crop_dir):
- os.makedirs(crop_dir)
- remote = photo.get_original_url()
- print remote
- fname = urllib.urlopen(remote)
- im = cStringIO.StringIO(fname.read()) # constructs a StringIO holding the image
- img = Image.open(im)
-
- #calculate crop:
- cur_width, cur_height = img.size
- new_width, new_height = 291, 350
- ratio = max(float(new_width)/cur_width,float(new_height)/cur_height)
- x = (cur_width * ratio)
- y = (cur_height * ratio)
- xd = abs(new_width - x)
- yd = abs(new_height - y)
- x_diff = int(xd / 2)
- y_diff = int(yd / 2)
- box = (int(x_diff), int(y_diff), int(x_diff+new_width), int(y_diff+new_height))
-
- #create resized file
- resized = img.resize((int(x), int(y)), Image.ANTIALIAS).crop(box)
- # save resized file
- resized_filename = '%s/%s.jpg' %(crop_dir, set.id)
- try:
- if img.format == 'JPEG':
- resized.save(resized_filename, 'JPEG', quality=95, optimize=True)
- else:
- resized.save(resized_filename)
- except IOError, e:
- if os.path.isfile(resized_filename):
- os.unlink(resized_filename)
- raise e
- #os.unlink(img)
-
-
-
-def sync_sets(*args, **kwargs):
- dupe = False # Set our dupe flag for the following loop
- BASE_PATH = 'http://flickr.com/services/rest/'
- client = FlickrClient(BASE_PATH, API_KEY)
- data = client.flickr_photosets_getList(user_id=settings.FLICKR_USER_ID)
- nodes = data.findall('photosets/photoset')
- for post in nodes:
- info = dict((k, smart_unicode(post.get(k))) for k in post.keys())
- try:
- row = PhotoGallery.objects.get(set_id__exact=info['id'])
- # okay it already exists, but is it up-to-date?
- #get_photos_in_set(row,set.id)
-
- except ObjectDoesNotExist:
- disregard = ['POTD 2008','Snow Day','Wedding','Some random stuff']
- if force_unicode(post.findtext('title')) in disregard:
- pass
- else:
- s = PhotoGallery.objects.create (
- set_id = force_unicode(info['id']),
- set_title = force_unicode(post.findtext('title')),
- set_desc = force_unicode(post.findtext('description')),
- set_slug = slugify(force_unicode(post.findtext('title'))),
- primary = force_unicode(info['primary']),
- )
- get_photos_in_set(s)
- #create the gallery thumbnail image:
- photo = Photo.objects.get(flickr_id__exact=str(info['primary']))
- make_gallery_thumb(photo,s)
-
-def get_photos_in_set(set):
- BASE_PATH = 'http://flickr.com/services/rest/'
- client = FlickrClient(BASE_PATH, API_KEY)
- data = client.flickr_photosets_getPhotos(user_id=settings.FLICKR_USER_ID, photoset_id=str(set.set_id))
- for post in data.findall('photoset/photo'):
- info = dict((k, smart_unicode(post.get(k))) for k in post.keys())
- photo = Photo.objects.get(flickr_id__exact=str(info['id']))
- set.photos.add(photo)
-
-
-"""
-def sync_flickr_comments(*args, **kwargs):
- cur_page = 1 # Start on the first page of the stream
- paginate_by = 100 # Get 100 photos at a time
- inc = 1 # Set our dupe flag for the following loop
- # Get our flickr client running
- client = FlickrClient(settings.FLICKR_API_KEY)
- # get total number of photos in stream
- total = client.flickr_people_getInfo(user_id=settings.FLICKR_USER_ID)
- total_num = safestr(total.person.photos.count)
- while (inc < int(total_num)):
- photos = client.flickr_people_getPublicPhotos(user_id=settings.FLICKR_USER_ID, page=cur_page, per_page=paginate_by,extras="date_upload,date_taken,geo")
- incr = 1
- for photo in photos.photos:
- do_photo_comments(photo("id"),photo("secret"))
- inc = inc+1
- incr = incr+1
- print cur_page
- if incr == 100:
- cur_page = cur_page+1
-
-
-
-def do_photo_comments(id, secret):
- # Get our flickr client running
- client = FlickrClient(settings.FLICKR_API_KEY)
- photo = Photo.objects.get(flickr_id=id, flickr_secret=secret)
- comments = client.flickr_photos_comments_getList(user_id=settings.FLICKR_USER_ID, photo_id=id)
- for item in comments.comments:
- try:
- item
- print item('authorname')
- dt = datetime.datetime.fromtimestamp(float(item('datecreate')))
- ctype = ContentType.objects.get_for_model(Photo)
- try:
- f = FreeComment.objects.get(content_type=ctype, object_id=photo.id, submit_date=dt)
- #print f.id
- except ObjectDoesNotExist:
- if safestr(item('authorname')) == 'luxagraf':
- mail = 'hyper@luxagraf.net'
- else:
- mail = slugify(item('authorname'))+'@flickr.com'
- c = FreeComment.objects.create (
- content_type = ctype,
- object_id = photo.id,
- comment = safestr(item),
- person_name = safestr(item('authorname')),
- person_email = mail,
- person_url = item('permalink'),
- is_public = True,
- site_id = 1,
- approved = 0,
- submit_date = dt
- )
-
- except AttributeError:
- pass
-
- def get_country_name(lat,long):
- name = GeoClient.findCountrySubdivision(lat,long, http_proxy=None)
- if name.countrySubdivision.countryCode.PCDATA == "US":
- r_name = "US-%s" %(force_unicode(STATE_LIST[name.countrySubdivision.adminCode1.PCDATA]))
- else:
- r_name = force_unicode(name.countrySubdivision.countryName.PCDATA)
- return r_name
-
-
-def create_size(self, photosize):
- if self.size_exists(photosize):
- return
- if not os.path.isdir(self.cache_path()):
- os.makedirs(self.cache_path())
- try:
- im = Image.open(self.get_image_filename())
- except IOError:
- return
- if im.size == photosize.size():
- shutil.copy(self.get_image_filename(),
- self._get_SIZE_path(photosize))
- return
- cur_width, cur_height = im.size
- new_width, new_height = photosize.size()
- if photosize.crop:
- ratio = max(float(new_width)/cur_width,float(new_height)/cur_height)
- x = (cur_width * ratio)
- y = (cur_height * ratio)
- xd = abs(new_width - x)
- yd = abs(new_height - y)
- x_diff = int(xd / 2)
- y_diff = int(yd / 2)
- if self.crop_from == 'top':
- box = (int(x_diff), 0, int(x_diff+new_width), new_height)
- elif self.crop_from == 'left':
- box = (0, int(y_diff), new_width, int(y_diff+new_height))
- elif self.crop_from == 'bottom':
- box = (int(x_diff), int(yd), int(x_diff+new_width), int(y)) # y - yd = new_height
- elif self.crop_from == 'right':
- box = (int(xd), int(y_diff), int(x), int(y_diff+new_height)) # x - xd = new_width
- else:
- box = (int(x_diff), int(y_diff), int(x_diff+new_width), int(y_diff+new_height))
- resized = im.resize((int(x), int(y)), Image.ANTIALIAS).crop(box)
- else:
- if not new_width == 0 and not new_height == 0:
- if cur_width > cur_height:
- ratio = float(new_width)/cur_width
- else:
- ratio = float(new_height)/cur_height
- else:
- if new_width == 0:
- ratio = float(new_height)/cur_height
- else:
- ratio = float(new_width)/cur_width
- resized = im.resize((int(cur_width*ratio), int(cur_height*ratio)), Image.ANTIALIAS)
-
- # Apply effect if found
- if self.effect is not None:
- resized = self.effect.process(resized)
- elif photosize.effect is not None:
- resized = photosize.effect.process(resized)
-
- # save resized file
- resized_filename = getattr(self, "get_%s_path" % photosize.name)()
- try:
- if im.format == 'JPEG':
- resized.save(resized_filename, 'JPEG', quality=int(photosize.quality),
- optimize=True)
- else:
- resized.save(resized_filename)
- except IOError, e:
- if os.path.isfile(resized_filename):
- os.unlink(resized_filename)
- raise e
-
-"""
-
-
-
-"""
-for p in photos.photos.photo:
- try:
- row = Photo.objects.get(flickr_id=p.id, flickr_secret=p.secret)
- # If the row exists already, set the dupe flag
- dupe = True
- #print 'already have '+p.id+' moving on'
- except ObjectDoesNotExist:
- #assign the photo to a place, uses "default" if the photo isn't near anything
- place = place_handler(force_unicode(p.latitude)+","+force_unicode(p.longitude))
- #Grab tags
- tags = client.flickr_photos_getInfo(user_id=settings.FLICKR_USER_ID, photo_id=force_unicode(p.id))
- # grab exif data
- exif = exif_handler(client.flickr_photos_getExif(user_id=API_KEY, photo_id=safestr(p.id)))
- # sort the exif data if it's available
- if exif.has_key("Aperture"):
- aperture = exif["Aperture"]
- else: aperture = ''
- if exif.has_key("Make"):
- make = exif["Make"]
- else: make = ''
- if exif.has_key("Model"):
- model = exif["Model"]
- else: model = ''
- if exif.has_key("Exposure"):
- exposure = exif["Exposure"]
- else: exposure = ''
- if exif.has_key("ISO Speed"):
- iso = exif["ISO Speed"]
- else: iso = ''
- if exif.has_key("Focal Length"):
- length = exif["Focal Length"]
- else: length = ''
- if exif.has_key("Date and Time (Original)"):
- dto = flickr_datetime_to_datetime(exif["Date and Time (Original)"].replace(':', '-', 2))
- else: dto = flickr_datetime_to_datetime(p.datetaken)
- photo = Photo.objects.create(
- title = p.title,
- flickr_id = p.id,
- flickr_owner = p.owner,
- flickr_server = p.server,
- flickr_secret = p.secret,
- flickr_originalsecret = tags.photo.originalsecret,
- flickr_farm = p.farm,
- pub_date = flickr_datetime_to_datetime(p.datetaken),
- description = force_unicode(tags.photo.description.PCDATA),
- exif_aperture = aperture,
- exif_make = make,
- exif_model = model,
- exif_shutter = exposure,
- exif_iso = iso,
- exif_lens = length,
- exif_date = dto,
- gps = force_unicode(p.latitude)+","+force_unicode(p.longitude),
- place = place,
- tags = str(", ".join(t.raw for t in tags.photo.tags.tag)).lower()
- )
- make_local_size(photo)
- #if (dupe):
- #break
-
-from locations.models import Location
-from photos.models import Photo
-from django.contrib.gis.geos import Point
-
-def find_loc(photos):
- for photo in photos:
- p = Point(photo.lon, photo.lat, srid=4326)
- try:
- loc = Location.objects.filter(geometry__contains=p).get()
- photo.location = loc
- print photo.id
- photo.save()
- except Location.DoesNotExist:
- print "photo %s does not fall within any exisiting location" %(photo.id)
-""" \ No newline at end of file
diff --git a/apps/photos/urls.py b/apps/photos/urls.py
deleted file mode 100644
index d917d85..0000000
--- a/apps/photos/urls.py
+++ /dev/null
@@ -1,13 +0,0 @@
-from django.conf.urls.defaults import *
-from django.views.generic import list_detail
-from django.views.generic.simple import redirect_to
-
-
-
-urlpatterns = patterns('',
- (r'data/(?P<slug>[-\w]+)/$', 'photos.views.photo_json'),
- (r'galleries/(?P<slug>[-\w]+)/$', 'photos.views.gallery'),
- (r'(?P<page>\d+)/$', 'photos.views.gallery_list'),
- (r'(?P<slug>[-\w]+)/$', redirect_to, {'url': '/photos/%(slug)s/1/'}),
- (r'', redirect_to, {'url': '/photos/1/'}),
-) \ No newline at end of file
diff --git a/apps/photos/views.py b/apps/photos/views.py
deleted file mode 100644
index 3edfccb..0000000
--- a/apps/photos/views.py
+++ /dev/null
@@ -1,50 +0,0 @@
-from django.shortcuts import render_to_response,get_object_or_404
-from django.template import RequestContext
-from django.views.generic.list_detail import object_list
-from django.http import Http404,HttpResponse
-from django.core import serializers
-
-
-from photos.models import Photo,PhotoGallery
-from locations.models import Country, Region
-
-
-
-def gallery_list(request,page):
- request.page_url = '/photos/%d/'
- request.page = int(page)
- qs = PhotoGallery.objects.all()
- return object_list(request, queryset=qs, template_name='archives/photos.html',extra_context={'page':page,})
-
-def gallery(request,slug):
- context = {
- 'object': PhotoGallery.objects.get(set_slug=slug)
- }
- return render_to_response('details/photo_galleries.html', context, context_instance = RequestContext(request))
-
-def photo_json(request, slug):
- p = PhotoGallery.objects.filter(set_slug=slug)
- return HttpResponse(serializers.serialize('json', p), mimetype='application/json')
-
-"""
-Grabs entries by region or country
-"""
-def gallery_list_by_area(request,slug,page):
- request.page_url = '/photos/'+slug+'/%d/'
- request.page = int(page)
- try:
- region = Region.objects.get(slug__exact=slug)
- qs = PhotoGallery.objects.filter(region = region).order_by('-id')
- except:
- region = Country.objects.get(slug__exact=slug)
- qs = PhotoGallery.objects.filter(location__state__country = region).order_by('-id')
- if not region:
- raise Http404
- context = {
- 'region': region,
- 'country_list': Country.objects.filter(visited=True),
- 'region_list': Region.objects.all(),
- 'page': page
- }
- return object_list(request, queryset=qs, template_name='archives/photos.html',
- extra_context=context)
diff --git a/apps/projects/__init__.py b/apps/projects/__init__.py
deleted file mode 100644
index e69de29..0000000
--- a/apps/projects/__init__.py
+++ /dev/null
diff --git a/apps/projects/admin.py b/apps/projects/admin.py
deleted file mode 100644
index 94c4780..0000000
--- a/apps/projects/admin.py
+++ /dev/null
@@ -1,182 +0,0 @@
-from django.contrib import admin
-from django import forms
-from django.contrib.gis.admin import OSMGeoAdmin
-from django.contrib.gis.maps.google import GoogleMap
-from django.conf import settings
-
-from projects.models.base import Project
-from projects.models.fiveby import FiveBy
-from projects.models.natparks import NationalParks
-
-
-GMAP = GoogleMap(key=settings.GOOGLE_MAPS_API_KEY)
-
-class ProjectAdmin(OSMGeoAdmin):
-
- list_display = ('title', 'pub_date', 'status',)
- search_fields = ['title', 'body_markdown']
- prepopulated_fields = {"slug" : ('title',)}
- list_filter = ('pub_date', 'status')
- fieldsets = (
- ('Project', {'fields': ('title','subtitle','lede', 'pub_date', 'model_name',('status','image',), 'slug',), 'classes': ('show','extrapretty','wide')}),
- )
-
- class Media:
- js = ['/media/admin/custom/model.js']
- extra_js = [GMAP.api_url + GMAP.key]
- map_template = 'gis/admin/google.html'
- #map_template = 'gis/admin/google.html'
- # Default GeoDjango OpenLayers map options
- # Uncomment and modify as desired
- # To learn more about this jargon visit:
- # www.openlayers.org
-
- default_lon = -9314310
- default_lat = 3991847
- default_zoom = 6
- #display_wkt = False
- #display_srid = False
- #extra_js = []
- #num_zoom = 18
- #max_zoom = False
- #min_zoom = False
- #units = False
- #max_resolution = False
- #max_extent = False
- #modifiable = True
- #mouse_position = True
- #scale_text = True
- #layerswitcher = True
- scrollable = False
- #admin_media_prefix = settings.ADMIN_MEDIA_PREFIX
- map_width = 700
- map_height = 325
- #map_srid = 4326
- #map_template = 'gis/admin/openlayers.html'
- #openlayers_url = 'http://openlayers.org/api/2.6/OpenLayers.js'
- #wms_url = 'http://labs.metacarta.com/wms/vmap0'
- #wms_layer = 'basic'
- #wms_name = 'OpenLayers WMS'
- #debug = False
- #widget = OpenLayersWidget
-
-class FiveByAdmin(OSMGeoAdmin):
-
- list_display = ('title', 'pub_date', 'status',)
- search_fields = ['title',]
- prepopulated_fields = {"slug" : ('title',)}
- list_filter = ('pub_date', 'status')
- fieldsets = (
- ('Project', {'fields': ('title','lede', 'pub_date', 'status',('image','videoh264','videoogg'), 'slug',('vimeo_link','youtube_link'),('point','location','region')), 'classes': ('show','extrapretty','wide')}),
- )
-
-
-
- class Media:
- js = ['/media/admin/custom/model.js']
- extra_js = [GMAP.api_url + GMAP.key]
- map_template = 'gis/admin/google.html'
- #map_template = 'gis/admin/google.html'
- # Default GeoDjango OpenLayers map options
- # Uncomment and modify as desired
- # To learn more about this jargon visit:
- # www.openlayers.org
-
- default_lon = -9314310
- default_lat = 3991847
- default_zoom = 6
- #display_wkt = False
- #display_srid = False
- #extra_js = []
- #num_zoom = 18
- #max_zoom = False
- #min_zoom = False
- #units = False
- #max_resolution = False
- #max_extent = False
- #modifiable = True
- #mouse_position = True
- #scale_text = True
- #layerswitcher = True
- scrollable = False
- #admin_media_prefix = settings.ADMIN_MEDIA_PREFIX
- map_width = 700
- map_height = 325
- #map_srid = 4326
- #map_template = 'gis/admin/openlayers.html'
- #openlayers_url = 'http://openlayers.org/api/2.6/OpenLayers.js'
- #wms_url = 'http://labs.metacarta.com/wms/vmap0'
- #wms_layer = 'basic'
- #wms_name = 'OpenLayers WMS'
- #debug = False
- #widget = OpenLayersWidget
-
-
-
-class NationalParksAdmin(OSMGeoAdmin):
-
- list_display = ('unit_name','type','state','name','visited', 'size')
- list_filter = ('state', 'type')
- search_fields = ['name',]
- fieldsets = (
- ('Project', {'fields': ('name', 'tag_line',('state','visited'),'dek','date_visited_begin','date_visited_end','mpoly','image',('post','gallery'),('url','size','fee', 'camping_fee','date_park_created'),'zoom'), 'classes': ('show','extrapretty','wide')}),
- )
-
-
-
- class Media:
- js = ['/media/admin/custom/model.js']
- extra_js = [GMAP.api_url + GMAP.key]
- map_template = 'gis/admin/google.html'
- #map_template = 'gis/admin/google.html'
- # Default GeoDjango OpenLayers map options
- # Uncomment and modify as desired
- # To learn more about this jargon visit:
- # www.openlayers.org
-
- default_lon = -9314310
- default_lat = 3991847
- default_zoom = 6
- #display_wkt = False
- #display_srid = False
- #extra_js = []
- #num_zoom = 18
- #max_zoom = False
- #min_zoom = False
- #units = False
- #max_resolution = False
- #max_extent = False
- #modifiable = True
- #mouse_position = True
- #scale_text = True
- #layerswitcher = True
- scrollable = False
- #admin_media_prefix = settings.ADMIN_MEDIA_PREFIX
- map_width = 700
- map_height = 325
- #map_srid = 4326
- #map_template = 'gis/admin/openlayers.html'
- #openlayers_url = 'http://openlayers.org/api/2.6/OpenLayers.js'
- #wms_url = 'http://labs.metacarta.com/wms/vmap0'
- #wms_layer = 'basic'
- #wms_name = 'OpenLayers WMS'
- #debug = False
- #widget = OpenLayersWidget
-
-from django.contrib import admin
-
-from projects.models.code import Code
-
-class CodeAdmin(admin.ModelAdmin):
- list_display = ('name', 'date_created', 'status')
- search_fields = ['name','body_html']
- list_filter = ['status',]
- fieldsets = (
- (None, {'fields': ('name','date_created','slug','status','body_html')}),
- )
-
-admin.site.register(Code, CodeAdmin)
-
-admin.site.register(Project, ProjectAdmin)
-admin.site.register(FiveBy, FiveByAdmin)
-admin.site.register(NationalParks, NationalParksAdmin) \ No newline at end of file
diff --git a/apps/projects/models/__init__.py b/apps/projects/models/__init__.py
deleted file mode 100644
index 7fe6077..0000000
--- a/apps/projects/models/__init__.py
+++ /dev/null
@@ -1,4 +0,0 @@
-from base import Project
-from fiveby import FiveBy
-from natparks import NationalParks
-from code import Code \ No newline at end of file
diff --git a/apps/projects/models/base.py b/apps/projects/models/base.py
deleted file mode 100644
index debb776..0000000
--- a/apps/projects/models/base.py
+++ /dev/null
@@ -1,75 +0,0 @@
-import datetime
-from django.contrib.gis.db import models
-from django.conf import settings
-from django.contrib.syndication.feeds import Feed
-from django.contrib.sitemaps import Sitemap
-from django.template.defaultfilters import truncatewords_html
-
-
-from utils import markdown2 as markdown
-
-
-from photos.models import PhotoGallery
-from locations.models import Location,Region
-
-
-def get_upload_path(self, filename):
- return "images/project-thumbs/%s/%s" %(datetime.datetime.today().strftime("%Y"), filename)
-
-def markdown_processor(md):
- html = markdown.markdown(md, safe_mode = False).split('<break>')
- return html
-
-
-
-class Project(models.Model):
- title = models.CharField(max_length=200)
- subtitle = models.CharField(max_length=200, null=True, blank=True)
- slug = models.SlugField(unique_for_date='pub_date')
- lede = models.TextField(blank=True)
- pub_date = models.DateTimeField('Date published')
- PUB_STATUS = (
- (0, 'Draft'),
- (1, 'Published'),
- )
- status = models.IntegerField(choices=PUB_STATUS, default=0)
- image = models.FileField(upload_to=get_upload_path, null=True,blank=True)
- model_name = models.CharField(max_length=200, null=True)
-
- @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
-
- class Meta:
- ordering = ('-pub_date',)
- get_latest_by = 'pub_date'
- app_label = 'projects'
-
- def __unicode__(self):
- return self.title
-
- def get_absolute_url(self):
- return "/%s/%s/" % ('projects', self.slug)
-
- def get_previous_published(self):
- return self.get_previous_by_pub_date(status__exact=1)
-
- def get_next_published(self):
- return self.get_next_by_pub_date(status__exact=1)
-
-
-class ProjectSitemap(Sitemap):
- changefreq = "monthly"
- priority = 0.5
-
- def items(self):
- return Project.objects.filter(status=1)
-
- def lastmod(self, obj):
- return obj.pub_date
diff --git a/apps/projects/models/code.py b/apps/projects/models/code.py
deleted file mode 100644
index 14a66f0..0000000
--- a/apps/projects/models/code.py
+++ /dev/null
@@ -1,25 +0,0 @@
-from django.db import models
-
-
-PUB_STATUS = (
- (0, 'Draft'),
- (1, 'Published'),
- )
-
-
-
-class Code(models.Model):
- name = models.CharField(max_length=254)
- slug = models.SlugField()
- date_created = models.DateField('Date Created')
- status = models.IntegerField(choices=PUB_STATUS, default=0)
- body_html = models.TextField(blank=True)
-
- class Meta:
- verbose_name_plural = "Code"
- app_label = 'projects'
- ordering = ('-date_created',)
- # Returns the string representation of the model.
- def __unicode__(self):
- return self.slug
-
diff --git a/apps/projects/models/fiveby.py b/apps/projects/models/fiveby.py
deleted file mode 100644
index 5415ee7..0000000
--- a/apps/projects/models/fiveby.py
+++ /dev/null
@@ -1,58 +0,0 @@
-import datetime
-from django.contrib.gis.db import models
-from django.conf import settings
-from django.contrib.syndication.feeds import Feed
-from django.contrib.sitemaps import Sitemap
-from django.template.defaultfilters import truncatewords_html
-
-from locations.models import Location,Region
-
-def get_upload_path(self, filename):
- return "images/projects/videos/5x5/%s/%s" %(datetime.datetime.today().strftime("%Y"), filename)
-
-def get_image_upload_path(self, filename):
- return "images/projects/5x5/%s/%s" %(datetime.datetime.today().strftime("%Y"), filename)
-
-class FiveBy(models.Model):
- title = models.CharField(max_length=200)
- slug = models.SlugField(unique_for_date='pub_date')
- lede = models.TextField(blank=True)
- image = models.FileField(upload_to=get_image_upload_path, null=True,blank=True)
- videoh264 = models.FileField(upload_to=get_upload_path, null=True,blank=True)
- videoogg = models.FileField(upload_to=get_upload_path, null=True,blank=True)
- vimeo_link = models.CharField(max_length=200)
- youtube_link = models.CharField(max_length=200)
- pub_date = models.DateTimeField('Date published')
- PUB_STATUS = (
- (0, 'Draft'),
- (1, 'Published'),
- )
- status = models.IntegerField(choices=PUB_STATUS, default=0)
- point = models.PointField(null=True)
- location = models.ForeignKey(Location, null=True)
- region = models.ForeignKey(Region, null=True)
-
-
-
- class Meta:
- ordering = ('-pub_date',)
- get_latest_by = 'pub_date'
- app_label = 'projects'
- verbose_name_plural = '5x5'
-
- def __unicode__(self):
- return self.title
-
- def get_absolute_url(self):
- return "/%s/%s/%s/" % ('projects', '5x5', self.slug)
-
- @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
- \ No newline at end of file
diff --git a/apps/projects/models/natparks.py b/apps/projects/models/natparks.py
deleted file mode 100644
index f4a739d..0000000
--- a/apps/projects/models/natparks.py
+++ /dev/null
@@ -1,56 +0,0 @@
-from django.contrib.gis.db import models
-from PIL import Image
-from blog.models import Entry
-from photos.models import PhotoGallery
-from locations.models import State
-
-
-PUB_STATUS = (
- (0, 'Draft'),
- (1, 'Published'),
- )
-
-
-import datetime
-def get_upload_path(self, filename):
- return "images/projects/np/%s/%s" %(datetime.datetime.today().strftime("%Y"), filename)
-
-
-class NationalParks(models.Model):
- type = models.CharField(max_length=50)
- name = models.CharField(max_length=254)
- state = models.ForeignKey(State, null=True)
- size = models.CharField(max_length=10, null=True)
- fee = models.CharField(max_length=5, null=True)
- camping_fee = models.CharField(max_length=10, null=True)
- url = models.CharField(max_length=250, null=True)
- code= models.CharField(max_length=16)
- unit_name= models.CharField(max_length=254)
- date_visited_begin = models.DateField('Date Visited',null=True)
- date_visited_end = models.DateField('Date Visited',null=True)
- date_park_created = models.DateField('Date Park Created',null=True)
- zoom= models.IntegerField(null=True)
- mpoly = models.MultiPolygonField(null=True)
- visited = models.BooleanField(default=False)
- dek = models.TextField(null=True, blank=True)
- tag_line = models.CharField(max_length=254, null=True)
- post = models.ForeignKey(Entry, null=True)
- gallery = models.ForeignKey(PhotoGallery, blank=True, null=True, verbose_name='photo set')
- image = models.FileField(upload_to=get_upload_path, null=True,blank=True,help_text="width: 980px, height: > 450px")
- image_height = models.CharField(max_length=20, null=True,blank=True)
- image_width = models.CharField(max_length=20, null=True,blank=True)
- objects = models.GeoManager()
-
- class Meta:
- verbose_name_plural = "National Parks"
- app_label = 'projects'
- ordering = ('-visited','unit_name',)
- # Returns the string representation of the model.
- def __unicode__(self):
- return self.unit_name
-
- def save(self):
- #get image dimensions
- img = Image.open(self.image)
- self.image_width, self.image_height = img.size
- super(NationalParks, self).save() \ No newline at end of file
diff --git a/apps/projects/shortcuts.py b/apps/projects/shortcuts.py
deleted file mode 100644
index d54410c..0000000
--- a/apps/projects/shortcuts.py
+++ /dev/null
@@ -1,235 +0,0 @@
-from django.contrib.gis.db.models.fields import GeometryField
-#from django.contrib.gis.gdal import Envelope
-from django.contrib.gis.geos import Polygon
-from django.utils import simplejson
-from django.http import HttpResponse
-#from django.db.models.fields.related import ManyRelatedManager
-
-# also need to check out:
-# http://code.google.com/p/dojango/source/browse/trunk/dojango/util/__init__.py#82
-
-
-# example usages:
-
-"""
-
-def a_shapes(request):
- ids = request.GET.get('ids').split(',')
- mimetype = 'text/plain' #'application/javascript; charset=utf8'
- pretty_print = True
- if ids:
- qs = WorldBorders.objects.filter(affiliates__in=ids).annotate(num_a=Count('affiliates')).filter(num_a__gt=0)
- else:
- qs = WorldBorders.objects.none()
- return render_to_geojson(qs,
- extra_attributes=['num_a','affiliates_set'],
- geom_attribute='point',
- included_fields=['id','name'],
- mimetype=mimetype,
- proj_transform=900913,
- pretty_print=pretty_print
- )
-
-def responses(qs,type_='countries',pretty_print=True,mimetype='text/plain'):
- if type_ == 'locations':
- qs = qs.geolocations()
- return render_to_geojson(qs,
- excluded_fields=['json'],
- geom_field='point',
- proj_transform=900913,
- mimetype=mimetype,
- pretty_print=pretty_print
- )
- elif type_ == 'affiliates':
- qs = qs.exclude(geokeywords='').attach_locations()
- return render_to_geojson(qs,
- included_fields=['id','_geokeywords_cache'],
- geom_attribute='point',
- extra_attributes=['name'],
- proj_transform=900913,
- mimetype=mimetype,
- pretty_print=pretty_print
- )
- elif type_ == 'countries':
- qs2 = W.objects.filter(affiliates__in=qs).annotate(num_a=Count('affiliates')).filter(num_a__gt=0)
- return render_to_geojson(qs2,
- extra_attributes=['num_a'],
- #geom_attribute='point',
- mimetype=mimetype,
- pretty_print=pretty_print
- )
- else:# type_ == 'countries' or type is None:
- if len(qs) > 10:
- # this is a limit, weird huh?
- # requires another all() otherwise it
- # returns a list!
- qs = qs.all()[:10]
- return render_to_geojson(qs,
- included_fields=['id','_geokeywords_cache'],
- geom_attribute='countries.unionagg',
- extra_attributes=['name'],
- mimetype=mimetype,
- pretty_print=pretty_print
- )
-"""
-
-
-
-def render_to_geojson(query_set, geom_field=None, geom_attribute=None, extra_attributes=[],mimetype='text/plain', pretty_print=False, excluded_fields=[],included_fields=[],proj_transform=None):
- '''
-
- Shortcut to render a GeoJson FeatureCollection from a Django QuerySet.
- Currently computes a bbox and adds a crs member as a sr.org link
-
- '''
- excluded_fields.append('_state')
- collection = {}
- if hasattr(query_set,'_meta'): # its a model instance
- fields = query_set._meta.fields
- query_set = [query_set]
- else:
- fields = query_set.model._meta.fields
-
- if geom_attribute:
- geometry_name = geom_attribute
- geo_field = None
- if '.' in geom_attribute:
- prop, meth = geom_attribute.split('.')
- if len(query_set):
- p = getattr(query_set[0],prop)
- geo_field = getattr(p,meth)
- if callable(geo_field):
- geo_field = geo_field()
- else:
- if len(query_set):
- geo_field = getattr(query_set[0],geom_attribute)
- if callable(geo_field):
- geo_field = geo_field()
- if not geo_field:
- srid = 4326
- else:
- srid = geo_field.srid
-
- else:
- geo_fields = [f for f in fields if isinstance(f, GeometryField)]
-
- #attempt to assign geom_field that was passed in
- if geom_field:
- #import pdb;pdb.set_trace()
- geo_fieldnames = [x.name for x in geo_fields]
- try:
- geo_field = geo_fields[geo_fieldnames.index(geom_field)]
- except:
- raise Exception('%s is not a valid geometry on this model' % geom_field)
- else:
- if not len(geo_fields):
- raise Exception('There appears to be no valid geometry on this model')
- geo_field = geo_fields[0] # no support yet for multiple geometry fields
-
-
- #remove other geom fields from showing up in attributes
- if len(geo_fields) > 1:
- for field in geo_fields:
- if field.name not in excluded_fields:
- excluded_fields.append(field.name)
-
- geometry_name = geo_field.name
-
-
- srid = geo_field.srid
-
- if proj_transform:
- to_srid = proj_transform
- else:
- to_srid = srid
- # Gather the projection information
- crs = {}
- crs['type'] = "link"
- crs_properties = {}
- crs_properties['href'] = 'http://spatialreference.org/ref/epsg/%s/' % to_srid
- crs_properties['type'] = 'proj4'
- crs['properties'] = crs_properties
- collection['crs'] = crs
- collection['srid'] = to_srid
-
- # Build list of features
- features = []
- if query_set.distinct():
- for item in query_set:
- feat = {}
- feat['type'] = 'Feature'
- if included_fields:
- d = {}
- for f in included_fields:
- if hasattr(item,f):
- d[f] = getattr(item,f)
- else:
- d = item.__dict__.copy()
- for field in excluded_fields:
- if field in d.keys():
- d.pop(field)
- if geometry_name in d:
- d.pop(geometry_name)
-
- for attr in extra_attributes:
- a = getattr(item,attr)
- # crappy way of trying to figure out it this is a
- # m2m, aka 'ManyRelatedManager'
- if hasattr(a,'values_list'):
- a = list(a.values_list('id',flat=True))
- if callable(a):
- d[attr] = a()
- else:
- d[attr] = a
- if '.' in geometry_name:
- prop, meth = geometry_name.split('.')
- a = getattr(item,prop)
- g = getattr(a,meth)
- if callable(g):
- g = g()
- else:
- g = getattr(item,geometry_name)
- if g:
- if proj_transform:
- g.transform(proj_transform)
- feat['geometry'] = simplejson.loads(g.geojson)
- feat['properties'] = d
- features.append(feat)
- else:
- pass #features.append({'type':'Feature','geometry': {},'properties':{}})
-
- # Label as FeatureCollection and add Features
- collection['type'] = "FeatureCollection"
- collection['features'] = features
-
- # Attach extent of all features
- if query_set:
- ex = None
- query_set.query.distinct = False
- if hasattr(query_set,'agg_extent'):
- ex = [x for x in query_set.agg_extent.tuple]
- elif '.' in geometry_name:
- prop, meth = geometry_name.split('.')
- a = getattr(item,prop)
- if a:
- ex = [x for x in a.extent()]
- else:
- # make sure qs does not have .distinct() in it...
- ex = [x for x in query_set.extent()]
- if ex:
- if proj_transform:
- poly = Polygon.from_bbox(ex)
- poly.srid = srid
- poly.transform(proj_transform)
- ex = poly.extent
- collection['bbox'] = ex
-
- # Return response
- response = HttpResponse()
- if pretty_print:
- response.write('%s' % simplejson.dumps(collection, indent=1))
- else:
- response.write('%s' % simplejson.dumps(collection))
- response['Content-length'] = str(len(response.content))
- response['Content-Type'] = mimetype
- return response \ No newline at end of file
diff --git a/apps/projects/urls.py b/apps/projects/urls.py
deleted file mode 100644
index 14722a8..0000000
--- a/apps/projects/urls.py
+++ /dev/null
@@ -1,17 +0,0 @@
-from django.conf.urls.defaults import *
-from django.views.generic.list_detail import object_list
-from django.views.generic.simple import redirect_to,direct_to_template
-from django.views.generic import list_detail
-
-from projects.models.base import Project
-
-projects = {
- 'queryset': Project.objects.filter(status__exact=1).order_by('-pub_date'),
-}
-
-urlpatterns = patterns('',
- (r'data/(?P<id>\d+)/$', 'projects.views.data_json'),
- (r'(?P<slug>[-\w]+)/$', 'projects.views.detail'),
- (r'^$',list_detail.object_list, dict(projects, template_name='archives/projects.html')),
-)
-
diff --git a/apps/projects/views.py b/apps/projects/views.py
deleted file mode 100644
index 64857a7..0000000
--- a/apps/projects/views.py
+++ /dev/null
@@ -1,38 +0,0 @@
-from django.shortcuts import render_to_response,get_object_or_404
-from django.template import RequestContext
-from django.views.generic.list_detail import object_list
-from django.db.models import get_model
-from django.http import HttpResponse
-from django.core import serializers
-
-from projects.shortcuts import render_to_geojson
-from projects.models.base import Project
-from projects.models.fiveby import FiveBy
-from projects.models.natparks import NationalParks
-
-projects = {'5x5':'FiveBy','6x6':'SixBy','national-parks':'NationalParks','code':'Code'}
-
-"""
-Projects by slug
-"""
-def detail(request,slug):
- name = projects[slug]
- model = get_model('projects', name)
- if slug == 'national-parks':
- qs = model.objects.filter(visited__exact=True).order_by("-date_visited_begin")
- else:
- qs = model.objects.filter(status__exact=1)
- template = 'details/%s.html' %(slug)
- return object_list(request, queryset=qs, template_name=template,)
-
-
-def data_json(request, id):
- qs = NationalParks.objects.filter(pk=id)
- return render_to_geojson(
- qs,
- included_fields=['id',],
- geom_attribute='mpoly',
- mimetype = 'application/json',
- pretty_print=True
- )
- \ No newline at end of file