summaryrefslogtreecommitdiff
path: root/app/unused_apps/projects
diff options
context:
space:
mode:
Diffstat (limited to 'app/unused_apps/projects')
-rw-r--r--app/unused_apps/projects/__init__.py0
-rw-r--r--app/unused_apps/projects/admin.py135
-rw-r--r--app/unused_apps/projects/models/__init__.py5
-rw-r--r--app/unused_apps/projects/models/base.py67
-rw-r--r--app/unused_apps/projects/models/fiveby.py53
-rw-r--r--app/unused_apps/projects/models/gifs.py26
-rw-r--r--app/unused_apps/projects/models/natparks.py55
-rw-r--r--app/unused_apps/projects/models/self_experiments.py56
-rw-r--r--app/unused_apps/projects/natparks.js94
-rw-r--r--app/unused_apps/projects/shortcuts.py235
-rw-r--r--app/unused_apps/projects/urls.py29
-rw-r--r--app/unused_apps/projects/views.py45
12 files changed, 800 insertions, 0 deletions
diff --git a/app/unused_apps/projects/__init__.py b/app/unused_apps/projects/__init__.py
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/app/unused_apps/projects/__init__.py
diff --git a/app/unused_apps/projects/admin.py b/app/unused_apps/projects/admin.py
new file mode 100644
index 0000000..040b867
--- /dev/null
+++ b/app/unused_apps/projects/admin.py
@@ -0,0 +1,135 @@
+from django.contrib import admin
+from django.contrib.gis.admin import OSMGeoAdmin
+
+from projects.models.base import Project
+from projects.models.fiveby import FiveBy
+from projects.models.natparks import NationalParks
+from projects.models.gifs import AnimatedGif
+from projects.models.self_experiments import Experiment
+
+
+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']
+
+
+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')}),
+ )
+
+ # options for OSM map Using custom ESRI topo map
+ default_lon = -9285175
+ default_lat = 4025046
+ default_zoom = 6
+ units = True
+ scrollable = False
+ map_width = 700
+ map_height = 425
+ map_template = 'gis/admin/osm.html'
+
+
+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'
+ )
+ }),
+ )
+
+ # options for OSM map Using custom ESRI topo map
+ default_lon = -9285175
+ default_lat = 4025046
+ default_zoom = 6
+ units = True
+ scrollable = False
+ map_width = 700
+ map_height = 425
+ map_template = 'gis/admin/osm.html'
+
+
+class AnimatedGifAdmin(admin.ModelAdmin):
+ list_display = ('title', 'date_created')
+ search_fields = ['title']
+ fieldsets = (
+ (None, {
+ 'fields': (
+ 'title',
+ 'gif',
+ 'date_created',
+ 'slug',
+ 'music_ogg',
+ 'music_mp3'
+ )
+ }),
+ )
+
+
+class ExperimentAdmin(admin.ModelAdmin):
+ list_display = ('title', 'date_start', 'date_end_projected', 'days_remaining')
+ search_fields = ['title']
+ fieldsets = (
+ (None, {
+ 'fields': (
+ 'title',
+ 'slug',
+ 'body_markdown',
+ ('date_start', 'duration', 'date_end_projected'),
+ 'date_end_actual',
+ 'status'
+ )
+ }),
+ )
+
+
+admin.site.register(Experiment, ExperimentAdmin)
+admin.site.register(AnimatedGif, AnimatedGifAdmin)
+admin.site.register(Project, ProjectAdmin)
+admin.site.register(FiveBy, FiveByAdmin)
+admin.site.register(NationalParks, NationalParksAdmin)
diff --git a/app/unused_apps/projects/models/__init__.py b/app/unused_apps/projects/models/__init__.py
new file mode 100644
index 0000000..3230ff4
--- /dev/null
+++ b/app/unused_apps/projects/models/__init__.py
@@ -0,0 +1,5 @@
+from .base import Project
+from .fiveby import FiveBy
+from .natparks import NationalParks
+from .gifs import AnimatedGif
+from .self_experiments import Experiment
diff --git a/app/unused_apps/projects/models/base.py b/app/unused_apps/projects/models/base.py
new file mode 100644
index 0000000..aa795d2
--- /dev/null
+++ b/app/unused_apps/projects/models/base.py
@@ -0,0 +1,67 @@
+import datetime
+from django.contrib.gis.db import models
+from django.contrib.sitemaps import Sitemap
+from django.conf import settings
+
+
+def get_upload_path(self, filename):
+ return "images/project-thumbs/%s/%s" % (datetime.datetime.today().strftime("%Y"), filename)
+
+
+class Project(models.Model):
+ title = models.CharField(max_length=200)
+ subtitle = models.CharField(max_length=200, null=True, blank=True)
+ slug = models.CharField(max_length=50)
+ 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
+
+ @property
+ def get_project_image(self):
+ return "%s%s" % (settings.IMAGES_URL, self.image.name[7:])
+
+
+ class Meta:
+ ordering = ('-pub_date',)
+ get_latest_by = 'pub_date'
+ app_label = 'projects'
+
+ def __str__(self):
+ return self.title
+
+ def get_absolute_url(self):
+ return "/%s/" % (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
+ protocol = "https"
+
+ def items(self):
+ return Project.objects.filter(status=1)
+
+ def lastmod(self, obj):
+ return obj.pub_date
diff --git a/app/unused_apps/projects/models/fiveby.py b/app/unused_apps/projects/models/fiveby.py
new file mode 100644
index 0000000..473c095
--- /dev/null
+++ b/app/unused_apps/projects/models/fiveby.py
@@ -0,0 +1,53 @@
+import datetime
+from django.contrib.gis.db import models
+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, on_delete=models.CASCADE, null=True)
+ region = models.ForeignKey(Region, on_delete=models.CASCADE, null=True)
+
+ class Meta:
+ ordering = ('-pub_date',)
+ get_latest_by = 'pub_date'
+ app_label = 'projects'
+ verbose_name_plural = '5x5'
+
+ def __str__(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
diff --git a/app/unused_apps/projects/models/gifs.py b/app/unused_apps/projects/models/gifs.py
new file mode 100644
index 0000000..25b8734
--- /dev/null
+++ b/app/unused_apps/projects/models/gifs.py
@@ -0,0 +1,26 @@
+import datetime
+from django.db import models
+
+
+def get_upload_path(self, filename):
+ return "images/projects/gifs/%s/%s" % (datetime.datetime.today().strftime("%Y"), filename)
+
+
+class AnimatedGif(models.Model):
+ title = models.CharField(max_length=254)
+ gif = models.ImageField(upload_to=get_upload_path)
+ slug = models.SlugField()
+ date_created = models.DateField('Date Created')
+ music_ogg = models.FileField(upload_to=get_upload_path, blank=True, null=True)
+ music_mp3 = models.FileField(upload_to=get_upload_path, blank=True, null=True)
+
+ class Meta:
+ verbose_name_plural = "Animated Gifs"
+ app_label = 'projects'
+ ordering = ('-date_created',)
+
+ def __str__(self):
+ return self.slug
+
+ def get_absolute_url(self):
+ return '/projects/gifs/%s/' % (self.slug)
diff --git a/app/unused_apps/projects/models/natparks.py b/app/unused_apps/projects/models/natparks.py
new file mode 100644
index 0000000..980d9fa
--- /dev/null
+++ b/app/unused_apps/projects/models/natparks.py
@@ -0,0 +1,55 @@
+import datetime
+from PIL import Image
+from django.contrib.gis.db import models
+from django.conf import settings
+from jrnl.models import Entry
+from photos.models import PhotoGallery
+from locations.models import State
+
+
+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, on_delete=models.CASCADE, 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, on_delete=models.CASCADE, null=True)
+ gallery = models.ForeignKey(PhotoGallery, on_delete=models.CASCADE, 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)
+
+ class Meta:
+ verbose_name_plural = "National Parks"
+ app_label = 'projects'
+ ordering = ('-visited', 'unit_name',)
+
+ def __str__(self):
+ return self.unit_name
+
+ @property
+ def get_image_url(self):
+ return "%s%s" % (settings.IMAGES_URL, self.image.name[7:])
+
+ def save(self):
+ #get image dimensions
+ img = Image.open(self.image)
+ self.image_width, self.image_height = img.size
+ super(NationalParks, self).save()
diff --git a/app/unused_apps/projects/models/self_experiments.py b/app/unused_apps/projects/models/self_experiments.py
new file mode 100644
index 0000000..be9d0b7
--- /dev/null
+++ b/app/unused_apps/projects/models/self_experiments.py
@@ -0,0 +1,56 @@
+import datetime
+from django.db import models
+
+import markdown
+
+PUB_STATUS = (
+ (0, 'Draft'),
+ (1, 'Published'),
+)
+
+
+def markdown_processor(md):
+ return markdown.markdown(md, ['footnotes'], safe_mode=False)
+
+
+class Experiment(models.Model):
+ title = models.CharField(max_length=254)
+ slug = models.SlugField()
+ date_created = models.DateField(auto_now_add=True)
+ date_start = models.DateField()
+ date_end_actual = models.DateField(blank=True, null=True)
+ date_end_projected = models.DateField(blank=True)
+ duration = models.PositiveSmallIntegerField(default=30)
+ status = models.IntegerField(choices=PUB_STATUS, default=0)
+ body_html = models.TextField(blank=True)
+ body_markdown = models.TextField()
+
+ class Meta:
+ app_label = 'projects'
+ ordering = ('-date_start',)
+
+ # Returns the string representation of the model.
+ def __str__(self):
+ return self.title
+
+ def get_absolute_url(self):
+ return "/projects/experiments/%s/%s/" % (self.pub_date.strftime("%Y").lower(), self.slug)
+
+ def days_remaining(self):
+ return self.date_end_projected - datetime.date.today()
+
+ @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 save(self):
+ self.body_html = markdown_processor(self.body_markdown)
+ self.date_end_projected = self.date_start + datetime.timedelta(self.duration)
+ super(Experiment, self).save()
diff --git a/app/unused_apps/projects/natparks.js b/app/unused_apps/projects/natparks.js
new file mode 100644
index 0000000..8481408
--- /dev/null
+++ b/app/unused_apps/projects/natparks.js
@@ -0,0 +1,94 @@
+//Utility functions for map info window
+function mapit(lat,lon,zoom,id) {
+ map = L.map(document.getElementById("map-wrapper-"+id));
+ centerCoord = new L.LatLng(lat, lon);
+ zoom = zoom;
+ L.tileLayer.provider('Esri.WorldTopoMap', {maxZoom: 18, attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Tiles &copy; Esri and the GIS User Community'}).addTo(map);
+ map.setView(centerCoord, zoom);
+ ////get the geojson for this map
+ $.ajax({
+ url: "/projects/data/natparks/"+id+".json",
+ dataType: "json",
+ success: function(data, text, request) { draw_poly(data, map); }
+ //complete: function(xhr, status) {console.log(status); return false; },
+ });
+ //draw the polygon
+ function draw_poly(data, map) {
+ var myStyle = {
+ "color": "#201a11",
+ "weight": 2,
+ "opacity": 0.65
+ };
+ L.geoJson(data, {
+ style: myStyle
+ }).addTo(map);
+ }
+}
+
+// utility functions to create/remove map container
+function create_map(obj) {
+ var lat = parseFloat(obj.attr('data-latitude'));
+ var lon = parseFloat(obj.attr('data-longitude'));
+ var zoom= parseInt(obj.attr('data-zoom'));
+ var id= obj.attr('data-id');
+
+ //create container divs
+ $(obj).parents().eq(3).append('<div class="map-container" id="map-container-'+id+'">');
+ $('#map-container-'+id).append('<div class="map-wrapper" id="map-wrapper-'+id+'">');
+ mapit(lat,lon,zoom,id);
+}
+function remove_map(id) {
+ $(id).remove();
+}
+
+//functions to handle the "more" link
+// utility functions to create/remove camera info container
+function get_exif(obj,id) {
+ //$(obj).parents().eq(2).append('<div id="exif-container">');
+ $(obj).parents().eq(3).append('<div class="more-container" id="'+id+'">'); $(obj).parents().eq(2).children('.meta').clone().appendTo('#'+id).css('visibility', 'visible');
+
+
+
+ //deal with the variable height of div.legend
+ $('#exif-container').css({
+ bottom: function(index, value) {
+ return parseFloat($(obj).parent().parent().css("height"))-14;
+ }
+ });
+}
+function remove_exif(id) {
+ $('#'+id).remove();
+}
+$(document).ready(function(){
+//set up click events for map button
+ $('.map-link').click( function() {
+ var more_id = 'more-container-'+$(this).parent().next().children('.more-link').attr('id').split('-')[1];
+ var id = '#map-container-'+$(this).attr('data-id');
+ if ($('#'+more_id).is(":visible")){
+ remove_exif(more_id);
+ }
+ if ($(id).is(":visible")) {
+ remove_map(id);
+ } else {
+ create_map($(this));
+ }
+ return false;
+
+ });
+
+ //set up click events for more info button
+ $('.more-link').click( function() {
+ var map_id = '#map-container-'+$(this).parent().prev().children('.map-link').attr('data-id');
+ var id = 'more-container-'+this.id.split('-')[1];
+ if ($(map_id).is(":visible")){
+ remove_map(map_id);
+ }
+ if ($('#'+id).is(":visible")) {
+ remove_exif(id);
+ } else {
+ get_exif(this, id);
+ }
+ return false;
+ });
+
+});
diff --git a/app/unused_apps/projects/shortcuts.py b/app/unused_apps/projects/shortcuts.py
new file mode 100644
index 0000000..90b1bb6
--- /dev/null
+++ b/app/unused_apps/projects/shortcuts.py
@@ -0,0 +1,235 @@
+from django.contrib.gis.db.models.fields import GeometryField
+#from django.contrib.gis.gdal import Envelope
+from django.contrib.gis.geos import Polygon
+import json
+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'] = json.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' % json.dumps(collection, indent=1))
+ else:
+ response.write('%s' % json.dumps(collection))
+ response['Content-length'] = str(len(response.content))
+ response['Content-Type'] = mimetype
+ return response
diff --git a/app/unused_apps/projects/urls.py b/app/unused_apps/projects/urls.py
new file mode 100644
index 0000000..8e56b16
--- /dev/null
+++ b/app/unused_apps/projects/urls.py
@@ -0,0 +1,29 @@
+from django.conf.urls import url
+from django.views.generic import ListView
+from projects.models.base import Project
+
+from . import views
+
+app_name = "project"
+
+urlpatterns = [
+ url(
+ r'data/(?P<id>\d+)/$',
+ views.data_json
+ ),
+ url(
+ r'gifs/(?P<slug>[-\w]+)/$',
+ views.gif_detail
+ ),
+ url(
+ r'(?P<slug>[-\w]+)/$',
+ views.detail
+ ),
+ url(
+ r'^$',
+ ListView.as_view(
+ queryset=Project.objects.filter(status__exact=1).order_by('-pub_date'),
+ template_name="archives/projects.html",
+ )
+ ),
+]
diff --git a/app/unused_apps/projects/views.py b/app/unused_apps/projects/views.py
new file mode 100644
index 0000000..ad5f167
--- /dev/null
+++ b/app/unused_apps/projects/views.py
@@ -0,0 +1,45 @@
+from django.shortcuts import render, get_object_or_404
+from django.template import RequestContext
+from django.apps import apps
+
+from projects.shortcuts import render_to_geojson
+from projects.models.natparks import NationalParks
+from projects.models.gifs import AnimatedGif
+
+projects = {
+ '5x5': 'FiveBy',
+ '6x6': 'SixBy',
+ 'national-parks': 'NationalParks',
+ 'code': 'Code'
+}
+
+
+def detail(request, slug):
+ """Projects by slug"""
+ name = projects[slug]
+ model = apps.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)
+ context = {
+ "object_list": qs,
+ }
+ template = 'details/%s.html' % (slug)
+ return render(request, template, context)
+
+
+def gif_detail(request, slug):
+ obj = get_object_or_404(AnimatedGif, slug__exact=slug)
+ return render(request, 'details/gifs.html', {'object': obj})
+
+
+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
+ )