summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorsubstantialnoninfringinguser <substantialnoninfringinguser@gmail.com>2009-07-03 05:31:49 +0100
committersubstantialnoninfringinguser <substantialnoninfringinguser@gmail.com>2009-07-03 05:31:49 +0100
commit8446047ab246b186f0404a1f8acbf719a6355a78 (patch)
treeb5b9a1b32c82383a1f6088bd4c4b97bacf933875
parentdc19150eba28de83e06c47d6235c07309f92b36d (diff)
downloadtroggle-8446047ab246b186f0404a1f8acbf719a6355a78.tar.gz
troggle-8446047ab246b186f0404a1f8acbf719a6355a78.tar.bz2
troggle-8446047ab246b186f0404a1f8acbf719a6355a78.zip
[svn] Brief code cleanup.
-rw-r--r--alwaysUseRequestContext.py8
-rw-r--r--core/models.py74
-rw-r--r--core/search.py39
-rw-r--r--core/views_caves.py22
-rw-r--r--core/views_logbooks.py22
-rw-r--r--core/views_other.py16
-rw-r--r--parsers/QMs.py2
-rw-r--r--parsers/cavetab.py2
-rw-r--r--parsers/logbooks.py2
-rw-r--r--parsers/people.py15
-rw-r--r--parsers/subcaves.py2
-rw-r--r--parsers/surveys.py2
-rw-r--r--profiles/views.py2
-rw-r--r--save_carefully.py29
-rw-r--r--templates/base.html4
-rw-r--r--templates/cavesearch.html23
-rw-r--r--utils.py69
17 files changed, 126 insertions, 207 deletions
diff --git a/alwaysUseRequestContext.py b/alwaysUseRequestContext.py
deleted file mode 100644
index b587b52..0000000
--- a/alwaysUseRequestContext.py
+++ /dev/null
@@ -1,8 +0,0 @@
-# this is the snippet from http://www.djangosnippets.org/snippets/3/
-
-from django.shortcuts import render_to_response
-from django.template import RequestContext
-
-def render_response(req, *args, **kwargs):
- kwargs['context_instance'] = RequestContext(req)
- return render_to_response(*args, **kwargs) \ No newline at end of file
diff --git a/core/models.py b/core/models.py
index 8dda56e..0c7e00d 100644
--- a/core/models.py
+++ b/core/models.py
@@ -18,8 +18,8 @@ logging.basicConfig(level=logging.DEBUG,
filename=settings.LOGFILE,
filemode='w')
-#This class is for adding fields and methods which all of our models will have.
class TroggleModel(models.Model):
+ """This class is for adding fields and methods which all of our models will have."""
new_since_parsing = models.BooleanField(default=False, editable=False)
non_public = models.BooleanField(default=False)
def object_name(self):
@@ -29,22 +29,10 @@ class TroggleModel(models.Model):
return urlparse.urljoin(settings.URL_ROOT, "/admin/core/" + self.object_name().lower() + "/" + str(self.pk))
class Meta:
- abstract = True
-
-class TroggleImageModel(ImageModel):
- new_since_parsing = models.BooleanField(default=False, editable=False)
-
- def object_name(self):
- return self._meta.object_name
-
- def get_admin_url(self):
- return urlparse.urljoin(settings.URL_ROOT, "/admin/core/" + self.object_name().lower() + "/" + str(self.pk))
-
-
- class Meta:
- abstract = True
+ abstract = True
class Expedition(TroggleModel):
+ """Represents a caving expedition"""
year = models.CharField(max_length=20, unique=True)
name = models.CharField(max_length=100)
date_from = models.DateField(blank=True,null=True)
@@ -61,15 +49,16 @@ class Expedition(TroggleModel):
#return settings.URL_ROOT + "/expedition/%s" % self.year
return urlparse.urljoin(settings.URL_ROOT, reverse('expedition',args=[self.year]))
-
# lose these two functions (inelegant, and we may create a file with the dates that we can load from)
def GuessDateFrom(self):
+ """Returns the date of the first logbook entry in the expedition"""
try:
return self.logbookentry_set.order_by('date')[0].date
except IndexError:
pass
- def GuessDateTo(self): # returns the date of the last logbook entry in the expedition
+ def GuessDateTo(self):
+ """Returns the date of the last logbook entry in the expedition"""
try:
return self.logbookentry_set.order_by('date')[-1].date
except IndexError:
@@ -90,42 +79,27 @@ class Expedition(TroggleModel):
date+=datetime.timedelta(days=1)
return res
-
-
-
class Person(TroggleModel):
+ """Represents a person, also used as the profile model"""
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
is_vfho = models.BooleanField(help_text="VFHO is the Vereines f&uuml;r H&ouml;hlenkunde in Obersteier, a nearby Austrian caving club.")
- mug_shot = models.CharField(max_length=100, blank=True,null=True)
+ mug_shot = models.CharField(max_length=100, blank=True,null=True) #obsolete, remove soon
blurb = models.TextField(blank=True,null=True)
+ orderref = models.CharField(max_length=200) # for alphabetic
- #href = models.CharField(max_length=200)
- orderref = models.CharField(max_length=200) # for alphabetic
-
- #the below have been removed and made methods. I'm not sure what the b in bisnotable stands for. - AC 16 Feb
- #notability = models.FloatField() # for listing the top 20 people
- #bisnotable = models.BooleanField()
user = models.OneToOneField(User, null=True, blank=True)
def get_absolute_url(self):
return urlparse.urljoin(settings.URL_ROOT,reverse('person',kwargs={'first_name':self.first_name,'last_name':self.last_name}))
class Meta:
- verbose_name_plural = "People"
- class Meta:
+ verbose_name_plural = "People"
ordering = ('orderref',) # "Wookey" makes too complex for: ('last_name', 'first_name')
def __unicode__(self):
if self.last_name:
return "%s %s" % (self.first_name, self.last_name)
return self.first_name
-
-# Below are no longer needed. Use {{ person.personexpedition_set.all.0.expedition }} for Firstexpedition, and {{ person.personexpedition_set.latest.expedition }} for Lastexpedition
- # these ought to be possible by piping through |min in the template, or getting the first of an ordered list
-# def Firstexpedition(self):
-# return self.personexpedition_set.order_by('expedition')[0]
-# def Lastexpedition(self):
-# return self.personexpedition_set.order_by('-expedition')[0]
def notability(self):
notability = Decimal(0)
@@ -136,18 +110,9 @@ class Person(TroggleModel):
def bisnotable(self):
return self.notability() > Decimal(1)/Decimal(3)
-
- #def Sethref(self):
- #if self.last_name:
- #self.href = self.first_name.lower() + "_" + self.last_name.lower()
- #self.orderref = self.last_name + " " + self.first_name
- #else:
- # self.href = self.first_name.lower()
- #self.orderref = self.first_name
- #self.notability = 0.0 # set temporarily
-
class PersonExpedition(TroggleModel):
+ """"""
expedition = models.ForeignKey(Expedition)
person = models.ForeignKey(Person)
date_from = models.DateField(blank=True,null=True)
@@ -234,8 +199,9 @@ class PersonExpedition(TroggleModel):
return urlparse.urljoin(settings.URL_ROOT, reverse('personexpedition',kwargs={'first_name':self.person.first_name,'last_name':self.person.last_name,'year':self.expedition.year}))
class LogbookEntry(TroggleModel):
+ """Represents trips of all kinds. This is the central model of Troggle."""
date = models.DateField()
- expedition = models.ForeignKey(Expedition,blank=True,null=True) # yes this is double-
+ expedition = models.ForeignKey(Expedition,blank=True,null=True)
author = models.ForeignKey(PersonExpedition,blank=True,null=True) # the person who writes it up doesn't have to have been on the trip.
# Re: the above- so this field should be "typist" or something, not "author". - AC 15 jun 09
title = models.CharField(max_length=200)
@@ -243,16 +209,9 @@ class LogbookEntry(TroggleModel):
place = models.CharField(max_length=100,blank=True,null=True,help_text="Only use this if you haven't chosen a cave")
text = models.TextField()
slug = models.SlugField(max_length=50)
- #href = models.CharField(max_length=100)
-
-
- #logbookentry_next = models.ForeignKey('LogbookEntry', related_name='pnext', blank=True,null=True)
- #logbookentry_prev = models.ForeignKey('LogbookEntry', related_name='pprev', blank=True,null=True)
class Meta:
- verbose_name_plural = "Logbook Entries"
- # several PersonTrips point in to this object
- class Meta:
+ verbose_name_plural = "Logbook Entries"
ordering = ('-date',)
def get_absolute_url(self):
@@ -302,7 +261,6 @@ class PersonTrip(TroggleModel):
except:
return
-# def get_persons_previous_trip(self):
#
# move following classes into models_cave
#
@@ -574,7 +532,7 @@ class QM(TroggleModel):
return res
photoFileStorage = FileSystemStorage(location=settings.PHOTOS_ROOT, base_url=settings.PHOTOS_URL)
-class Photo(TroggleImageModel):
+class Photo(ImageModel, TroggleModel):
caption = models.CharField(max_length=1000,blank=True,null=True)
contains_logbookentry = models.ForeignKey(LogbookEntry,blank=True,null=True)
contains_person = models.ManyToManyField(Person,blank=True,null=True)
@@ -606,7 +564,7 @@ def get_scan_path(instance, filename):
number="%02d" % instance.survey.wallet_number + str(instance.survey.wallet_letter) #using %02d string formatting because convention was 2009#01
return os.path.join('./',year,year+r'#'+number,instance.contents+str(instance.number_in_wallet)+r'.jpg')
-class ScannedImage(TroggleImageModel):
+class ScannedImage(ImageModel, TroggleModel):
file = models.ImageField(storage=scansFileStorage, upload_to=get_scan_path)
scanned_by = models.ForeignKey(Person,blank=True, null=True)
scanned_on = models.DateField(null=True)
diff --git a/core/search.py b/core/search.py
deleted file mode 100644
index 5ec2ce2..0000000
--- a/core/search.py
+++ /dev/null
@@ -1,39 +0,0 @@
-import re
-
-from django.db.models import Q
-
-# search script from http://www.julienphalip.com/blog/2008/08/16/adding-search-django-site-snap/
-
-def normalize_query(query_string,
- findterms=re.compile(r'"([^"]+)"|(\S+)').findall,
- normspace=re.compile(r'\s{2,}').sub):
- ''' Splits the query string in invidual keywords, getting rid of unecessary spaces
- and grouping quoted words together.
- Example:
-
- >>> normalize_query(' some random words "with quotes " and spaces')
- ['some', 'random', 'words', 'with quotes', 'and', 'spaces']
-
- '''
- return [normspace(' ', (t[0] or t[1]).strip()) for t in findterms(query_string)]
-
-def get_query(query_string, search_fields):
- ''' Returns a query, that is a combination of Q objects. That combination
- aims to search keywords within a model by testing the given search fields.
-
- '''
- query = None # Query to search for every search term
- terms = normalize_query(query_string)
- for term in terms:
- or_query = None # Query to search for a given term in each field
- for field_name in search_fields:
- q = Q(**{"%s__icontains" % field_name: term})
- if or_query is None:
- or_query = q
- else:
- or_query = or_query | q
- if query is None:
- query = or_query
- else:
- query = query & or_query
- return query \ No newline at end of file
diff --git a/core/views_caves.py b/core/views_caves.py
index f4327f3..b51fb0b 100644
--- a/core/views_caves.py
+++ b/core/views_caves.py
@@ -4,7 +4,7 @@ import troggle.settings as settings
from django.forms.models import formset_factory
import search
from django.core.urlresolvers import reverse
-from troggle.alwaysUseRequestContext import render_response # see views_logbooks for explanation on this.
+from utils import render_with_context # see views_logbooks for explanation on this.
from django.http import HttpResponseRedirect
from django.conf import settings
import re, urlparse
@@ -21,20 +21,20 @@ def caveindex(request):
caves = Cave.objects.all()
notablecavehrefs = [ "161", "204", "258", "76" ] # could detect notability by trips and notability of people who have been down them
notablecaves = [Cave.objects.get(kataster_number=kataster_number) for kataster_number in notablecavehrefs ]
- return render_response(request,'caveindex.html', {'caves': caves, 'notablecaves':notablecaves})
+ return render_with_context(request,'caveindex.html', {'caves': caves, 'notablecaves':notablecaves})
def cave(request, cave_id='', offical_name=''):
cave=getCave(cave_id)
if cave.non_public and not request.user.is_authenticated():
- return render_response(request,'nonpublic.html', {'instance': cave})
+ return render_with_context(request,'nonpublic.html', {'instance': cave})
else:
- return render_response(request,'cave.html', {'cave': cave})
+ return render_with_context(request,'cave.html', {'cave': cave})
def qm(request,cave_id,qm_id,year,grade=None):
year=int(year)
try:
qm=getCave(cave_id).get_QMs().get(number=qm_id,found_by__date__year=year)
- return render_response(request,'qm.html',locals())
+ return render_with_context(request,'qm.html',locals())
except QM.DoesNotExist:
url=urlparse.urljoin(settings.URL_ROOT, r'/admin/expo/qm/add/'+'?'+ r'number=' + qm_id)
@@ -46,7 +46,7 @@ def qm(request,cave_id,qm_id,year,grade=None):
def ent(request, cave_id, ent_letter):
cave = Cave.objects.filter(kataster_number = cave_id)[0]
cave_and_ent = CaveAndEntrance.objects.filter(cave = cave).filter(entrance_letter = ent_letter)[0]
- return render_response(request,'entrance.html', {'cave': cave,
+ return render_with_context(request,'entrance.html', {'cave': cave,
'entrance': cave_and_ent.entrance,
'letter': cave_and_ent.entrance_letter,})
@@ -54,7 +54,7 @@ def survexblock(request, survexpath):
survexblock = models.SurvexBlock.objects.get(survexpath=survexpath)
#ftext = survexblock.filecontents()
ftext = survexblock.text
- return render_response(request,'survexblock.html', {'survexblock':survexblock, 'ftext':ftext, })
+ return render_with_context(request,'survexblock.html', {'survexblock':survexblock, 'ftext':ftext, })
def subcave(request, cave_id, subcave):
print subcave
@@ -67,7 +67,7 @@ def subcave(request, cave_id, subcave):
if subcaveUrlSegment:
subcave=subcave.children.get(title=subcaveUrlSegment)
print subcave
- return render_response(request,'subcave.html', {'subcave': subcave,'cave':cave})
+ return render_with_context(request,'subcave.html', {'subcave': subcave,'cave':cave})
def caveSearch(request):
query_string = ''
@@ -77,13 +77,13 @@ def caveSearch(request):
entry_query = search.get_query(query_string, ['underground_description','official_name',])
found_entries = Cave.objects.filter(entry_query)
- return render_response(request,'cavesearch.html',
+ return render_with_context(request,'cavesearch.html',
{ 'query_string': query_string, 'found_entries': found_entries,})
def surveyindex(request):
surveys=Survey.objects.all()
expeditions=Expedition.objects.order_by("-year")
- return render_response(request,'survey.html',locals())
+ return render_with_context(request,'survey.html',locals())
def survey(request,year,wallet_number):
surveys=Survey.objects.all()
@@ -96,4 +96,4 @@ def survey(request,year,wallet_number):
planSketches=current_survey.scannedimage_set.filter(contents='plan')
elevationSketches=current_survey.scannedimage_set.filter(contents='elevation')
- return render_response(request,'survey.html', locals())
+ return render_with_context(request,'survey.html', locals())
diff --git a/core/views_logbooks.py b/core/views_logbooks.py
index 5fa550c..351d648 100644
--- a/core/views_logbooks.py
+++ b/core/views_logbooks.py
@@ -5,11 +5,11 @@ from django.db import models
from troggle.parsers.logbooks import LoadLogbookForExpedition
from troggle.parsers.people import GetPersonExpeditionNameLookup
from troggle.core.forms import PersonForm
-from django.core.urlresolvers import reverse
+from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
-# Django uses Context, not RequestContext when you call render_to_response. We always want to use RequestContext, so that django adds the context from settings.TEMPLATE_CONTEXT_PROCESSORS. This way we automatically get necessary settings variables passed to each template. So we use a custom method, render_response instead of render_to_response. Hopefully future Django releases will make this unnecessary.
-from troggle.alwaysUseRequestContext import render_response
+
+from utils import render_with_context
import search
import re
@@ -37,7 +37,7 @@ def personindex(request):
if person.bisnotable():
notablepersons.append(person)
- return render_response(request,'personindex.html', {'persons': persons, 'personss':personss, 'notablepersons':notablepersons, })
+ return render_with_context(request,'personindex.html', {'persons': persons, 'personss':personss, 'notablepersons':notablepersons, })
def expedition(request, expeditionname):
year = int(expeditionname)
@@ -49,7 +49,7 @@ def expedition(request, expeditionname):
message = LoadLogbookForExpedition(expedition)
#message = str(GetPersonExpeditionNameLookup(expedition).keys())
logbookentries = expedition.logbookentry_set.order_by('date')
- return render_response(request,'expedition.html', {'expedition': expedition, 'expedition_next':expedition_next, 'expedition_prev':expedition_prev, 'logbookentries':logbookentries, 'message':message, })
+ return render_with_context(request,'expedition.html', {'expedition': expedition, 'expedition_next':expedition_next, 'expedition_prev':expedition_prev, 'logbookentries':logbookentries, 'message':message, })
def get_absolute_url(self):
return ('expedition', (expedition.year))
@@ -64,7 +64,7 @@ def person(request, first_name='', last_name='', ):
person.save()
return HttpResponseRedirect(reverse('profiles_select_profile'))
- return render_response(request,'person.html', {'person': person, })
+ return render_with_context(request,'person.html', {'person': person, })
def get_absolute_url(self):
return settings.URL_ROOT + self.first_name + '_' + self.last_name
@@ -77,7 +77,7 @@ def personexpedition(request, first_name='', last_name='', year=''):
person = Person.objects.get(first_name = first_name, last_name = last_name)
expedition = Expedition.objects.get(year=year)
personexpedition = person.personexpedition_set.get(expedition=expedition)
- return render_response(request,'personexpedition.html', {'personexpedition': personexpedition, })
+ return render_with_context(request,'personexpedition.html', {'personexpedition': personexpedition, })
def newQMlink(logbookentry):
biggestQMnumber=0
@@ -101,10 +101,10 @@ def logbookentry(request, date, slug):
logbookentry = LogbookEntry.objects.filter(date=date, slug=slug)
if len(logbookentry)>1:
- return render_response(request, 'object_list.html',{'object_list':logbookentry})
+ return render_with_context(request, 'object_list.html',{'object_list':logbookentry})
else:
logbookentry=logbookentry[0]
- return render_response(request, 'logbookentry.html', {'logbookentry': logbookentry, 'newQMlink':newQMlink(logbookentry)})
+ return render_with_context(request, 'logbookentry.html', {'logbookentry': logbookentry, 'newQMlink':newQMlink(logbookentry)})
def logbookSearch(request, extra):
query_string = ''
@@ -114,11 +114,11 @@ def logbookSearch(request, extra):
entry_query = search.get_query(query_string, ['text','title',])
found_entries = LogbookEntry.objects.filter(entry_query)
- return render_response(request,'logbooksearch.html',
+ return render_with_context(request,'logbooksearch.html',
{ 'query_string': query_string, 'found_entries': found_entries, })
#context_instance=RequestContext(request))
def personForm(request,pk):
person=Person.objects.get(pk=pk)
form=PersonForm(instance=person)
- return render_response(request,'personform.html', {'form':form,}) \ No newline at end of file
+ return render_with_context(request,'personform.html', {'form':form,}) \ No newline at end of file
diff --git a/core/views_other.py b/core/views_other.py
index b3da852..07a4a75 100644
--- a/core/views_other.py
+++ b/core/views_other.py
@@ -8,7 +8,7 @@ import re
import randSent
from django.http import HttpResponse, HttpResponseRedirect
from django.core.urlresolvers import reverse
-from troggle.alwaysUseRequestContext import render_response # see views_logbooks for explanation on this.
+from utils import render_with_context
from core.models import *
def showrequest(request):
@@ -20,7 +20,7 @@ def stats(request):
statsDict['caveCount'] = int(Cave.objects.count())
statsDict['personCount'] = int(Person.objects.count())
statsDict['logbookEntryCount'] = int(LogbookEntry.objects.count())
- return render_response(request,'statistics.html', statsDict)
+ return render_with_context(request,'statistics.html', statsDict)
def frontpage(request):
message = "no test message" #reverse('personn', kwargs={"name":"hkjhjh"})
@@ -37,7 +37,7 @@ def frontpage(request):
cave = Cave
photo = Photo
from django.contrib.admin.templatetags import log
- return render_response(request,'frontpage.html', locals())
+ return render_with_context(request,'frontpage.html', locals())
def todo(request):
message = "no test message" #reverse('personn', kwargs={"name":"hkjhjh"})
@@ -51,7 +51,7 @@ def todo(request):
#'randSent':randSent.randomLogbookSentence(),
expeditions = Expedition.objects.order_by("-year")
totallogbookentries = LogbookEntry.objects.count()
- return render_response(request,'index.html', {'expeditions':expeditions, 'all':'all', 'totallogbookentries':totallogbookentries, "message":message})
+ return render_with_context(request,'index.html', {'expeditions':expeditions, 'all':'all', 'totallogbookentries':totallogbookentries, "message":message})
def calendar(request,year):
week=['S','S','M','T','W','T','F']
@@ -59,7 +59,7 @@ def calendar(request,year):
expedition=Expedition.objects.get(year=year)
PersonExpeditions=expedition.personexpedition_set.all()
- return render_response(request,'calendar.html', locals())
+ return render_with_context(request,'calendar.html', locals())
def controlPanel(request):
jobs_completed=[]
@@ -77,11 +77,11 @@ def controlPanel(request):
jobs_completed.append(item)
else:
if request.user.is_authenticated(): #The user is logged in, but is not a superuser.
- return render_response(request,'controlPanel.html', {'caves':Cave.objects.all(),'error':'You must be a superuser to use that feature.'})
+ return render_with_context(request,'controlPanel.html', {'caves':Cave.objects.all(),'error':'You must be a superuser to use that feature.'})
else:
return HttpResponseRedirect(reverse('auth_login'))
- return render_response(request,'controlPanel.html', {'caves':Cave.objects.all(),'expeditions':Expedition.objects.all(),'jobs_completed':jobs_completed})
+ return render_with_context(request,'controlPanel.html', {'caves':Cave.objects.all(),'expeditions':Expedition.objects.all(),'jobs_completed':jobs_completed})
def downloadCavetab(request):
from export import tocavetab
@@ -152,4 +152,4 @@ def ajax_test(request):
mimetype="application/json")
def eyecandy(request):
- return render_response(request,'eyecandy.html', {})
+ return render_with_context(request,'eyecandy.html', {})
diff --git a/parsers/QMs.py b/parsers/QMs.py
index b259bf1..f77207f 100644
--- a/parsers/QMs.py
+++ b/parsers/QMs.py
@@ -4,7 +4,7 @@ import csv
from django.conf import settings
from core.models import QM, LogbookEntry, Cave
from datetime import *
-from troggle.save_carefully import save_carefully
+from utils import save_carefully
import re, os
def deleteQMs():
diff --git a/parsers/cavetab.py b/parsers/cavetab.py
index 1a73f9e..0c7b985 100644
--- a/parsers/cavetab.py
+++ b/parsers/cavetab.py
@@ -2,7 +2,7 @@
import troggle.core.models as models
from django.conf import settings
import csv, time, re, os, logging
-from troggle.save_carefully import save_carefully
+from utils import save_carefully
##format of CAVETAB2.CSV is
KatasterNumber = 0
diff --git a/parsers/logbooks.py b/parsers/logbooks.py
index 70805ca..c6dfa79 100644
--- a/parsers/logbooks.py
+++ b/parsers/logbooks.py
@@ -13,7 +13,7 @@ import re
import datetime
import os
-from troggle.save_carefully import save_carefully
+from utils import save_carefully
#
# When we edit logbook entries, allow a "?" after any piece of data to say we've frigged it and
diff --git a/parsers/people.py b/parsers/people.py
index a74e827..fd269e6 100644
--- a/parsers/people.py
+++ b/parsers/people.py
@@ -3,18 +3,7 @@
from django.conf import settings
import core.models as models
import csv, re, datetime, os, shutil
-from troggle.save_carefully import save_carefully
-
-# Julian: the below code was causing errors and it seems like a duplication of the above. Hope I haven't broken anything by commenting it. -Aaron
-#
-# if name in expoers2008:
-# print "2008:", name
-# expomissing.discard(name) # I got an error which I think was caused by this -- python complained that a set changed size during iteration.
-# yo = models.Expedition.objects.filter(year = "2008")[0]
-# pyo = models.PersonExpedition(person = pObject, expedition = yo, is_guest=is_guest)
-# pyo.save()
-
-
+from utils import save_carefully
def saveMugShot(mugShotPath, mugShotFilename, person):
if mugShotFilename.startswith(r'i/'): #if filename in cell has the directory attached (I think they all do), remove it
@@ -39,7 +28,7 @@ def saveMugShot(mugShotPath, mugShotFilename, person):
mugShotObj.save()
def parseMugShotAndBlurb(personline, header, person):
- #create mugshot Photo instance
+ """create mugshot Photo instance"""
mugShotFilename=personline[header["Mugshot"]]
mugShotPath = os.path.join(settings.EXPOWEB, "folk", mugShotFilename)
if mugShotPath[-3:]=='jpg': #if person just has an image, add it
diff --git a/parsers/subcaves.py b/parsers/subcaves.py
index b8ee4d2..c3acc4d 100644
--- a/parsers/subcaves.py
+++ b/parsers/subcaves.py
@@ -7,7 +7,7 @@ import sys, os
import os, re, logging
from django.conf import settings
from core.models import Subcave, Cave
-from troggle.save_carefully import save_carefully
+from utils import save_carefully
def getLinksInCaveDescription(cave):
'''
diff --git a/parsers/surveys.py b/parsers/surveys.py
index 0a15d25..fc7fb7f 100644
--- a/parsers/surveys.py
+++ b/parsers/surveys.py
@@ -10,7 +10,7 @@ from PIL import Image
import csv
import re
import datetime
-from save_carefully import save_carefully
+from utils import save_carefully
def get_or_create_placeholder(year):
""" All surveys must be related to a logbookentry. We don't have a way to
diff --git a/profiles/views.py b/profiles/views.py
index aca2a6a..dec1172 100644
--- a/profiles/views.py
+++ b/profiles/views.py
@@ -16,8 +16,6 @@ from django import forms
from core.models import Person
-from troggle.alwaysUseRequestContext import render_response
-
from profiles import utils
from django.conf import settings
diff --git a/save_carefully.py b/save_carefully.py
deleted file mode 100644
index bacd91d..0000000
--- a/save_carefully.py
+++ /dev/null
@@ -1,29 +0,0 @@
-import logging
-
-def save_carefully(objectType, lookupAttribs={}, nonLookupAttribs={}):
- """Looks up instance using lookupAttribs and carries out the following:
- -if instance does not exist in DB: add instance to DB, return (new instance, True)
- -if instance exists in DB and was modified using Troggle: do nothing, return (existing instance, False)
- -if instance exists in DB and was not modified using Troggle: overwrite instance, return (instance, False)
-
- The checking is accomplished using Django's get_or_create and the new_since_parsing boolean field
- defined in core.models.TroggleModel.
-
- """
-
- instance, created=objectType.objects.get_or_create(defaults=nonLookupAttribs, **lookupAttribs)
-
- if not created and not instance.new_since_parsing:
- for k, v in nonLookupAttribs.items(): #overwrite the existing attributes from the logbook text (except date and title)
- setattr(instance, k, v)
- instance.save()
-
- if created:
- logging.info(unicode(instance)+u' was just added to the database for the first time. \n')
-
- if not created and instance.new_since_parsing:
- logging.info(unicode(instance)+" has been modified using Troggle, so the current script left it as is. \n")
-
- if not created and not instance.new_since_parsing:
- logging.info(unicode(instance)+" existed in the database unchanged since last parse. It was overwritten by the current script. \n")
- return (instance, created) \ No newline at end of file
diff --git a/templates/base.html b/templates/base.html
index 9813c7e..5be9d0f 100644
--- a/templates/base.html
+++ b/templates/base.html
@@ -47,6 +47,10 @@
<div id="related">
{% block related %}
+<script language="javascript">
+ $('#related').remove()
+ /*This is a hack to stop a line appearing because of the empty div border*/
+</script>
{% endblock %}
</div>
diff --git a/templates/cavesearch.html b/templates/cavesearch.html
deleted file mode 100644
index a555b44..0000000
--- a/templates/cavesearch.html
+++ /dev/null
@@ -1,23 +0,0 @@
-{% extends "base.html" %}
-{% load wiki_markup %}
-{% block title %}
-Cave search results for "{{ query_string }}"
-{% endblock%}
-
-{% block content %}
-
-<h1> Troggle cave search </h1>
-
-Your search string, <b>{{ query_string }}</b>,
-
-{% if found_entries %}
- was found in the following <b>{{found_entries.count}}</b> cave underground descriptions and / or official names:
- <ul>
- {% for cave in found_entries %}
- <li><a href="{{ settings.URL_ROOT }}cave/{{ cave.kataster_number }}">{{ cave|wiki_to_html_short }} : {{cave.official_name|wiki_to_html_short }}</a></li>
- {% endfor %}
- </ul>
- {% else %}
- was not found in any cave underground descriptions and / or official names. Please try again.
- {% endif %}
-{% endblock %} \ No newline at end of file
diff --git a/utils.py b/utils.py
new file mode 100644
index 0000000..4eced09
--- /dev/null
+++ b/utils.py
@@ -0,0 +1,69 @@
+from django.conf import settings
+from troggle.core.models import LogbookEntry
+import random, re, logging
+
+def weighted_choice(lst):
+ n = random.uniform(0,1)
+ for item, weight in lst:
+ if n < weight:
+ break
+ n = n - weight
+ return item
+
+def randomLogbookSentence():
+ randSent={}
+
+ # needs to handle empty logbooks without crashing
+
+ #Choose a random logbook entry
+ randSent['entry']=LogbookEntry.objects.order_by('?')[0]
+
+ #Choose again if there are no sentances (this happens if it is a placeholder entry)
+ while len(re.findall('[A-Z].*?\.',randSent['entry'].text))==0:
+ randSent['entry']=LogbookEntry.objects.order_by('?')[0]
+
+ #Choose a random sentence from that entry. Store the sentence as randSent['sentence'], and the number of that sentence in the entry as randSent['number']
+ sentenceList=re.findall('[A-Z].*?\.',randSent['entry'].text)
+ randSent['number']=random.randrange(0,len(sentenceList))
+ randSent['sentence']=sentenceList[randSent['number']]
+
+ return randSent
+
+
+def save_carefully(objectType, lookupAttribs={}, nonLookupAttribs={}):
+ """Looks up instance using lookupAttribs and carries out the following:
+ -if instance does not exist in DB: add instance to DB, return (new instance, True)
+ -if instance exists in DB and was modified using Troggle: do nothing, return (existing instance, False)
+ -if instance exists in DB and was not modified using Troggle: overwrite instance, return (instance, False)
+
+ The checking is accomplished using Django's get_or_create and the new_since_parsing boolean field
+ defined in core.models.TroggleModel.
+
+ """
+
+ instance, created=objectType.objects.get_or_create(defaults=nonLookupAttribs, **lookupAttribs)
+
+ if not created and not instance.new_since_parsing:
+ for k, v in nonLookupAttribs.items(): #overwrite the existing attributes from the logbook text (except date and title)
+ setattr(instance, k, v)
+ instance.save()
+
+ if created:
+ logging.info(unicode(instance)+u' was just added to the database for the first time. \n')
+
+ if not created and instance.new_since_parsing:
+ logging.info(unicode(instance)+" has been modified using Troggle, so the current script left it as is. \n")
+
+ if not created and not instance.new_since_parsing:
+ logging.info(unicode(instance)+" existed in the database unchanged since last parse. It was overwritten by the current script. \n")
+ return (instance, created)
+
+def render_with_context(req, *args, **kwargs):
+ """this is the snippet from http://www.djangosnippets.org/snippets/3/
+
+ Django uses Context, not RequestContext when you call render_to_response. We always want to use RequestContext, so that django adds the context from settings.TEMPLATE_CONTEXT_PROCESSORS. This way we automatically get necessary settings variables passed to each template. So we use a custom method, render_response instead of render_to_response. Hopefully future Django releases will make this unnecessary."""
+
+ from django.shortcuts import render_to_response
+ from django.template import RequestContext
+ kwargs['context_instance'] = RequestContext(req)
+ return render_to_response(*args, **kwargs) \ No newline at end of file