diff --git a/core/forms.py b/core/forms.py index 01a9cbe..2a54428 100644 --- a/core/forms.py +++ b/core/forms.py @@ -1,5 +1,5 @@ from django.forms import ModelForm -from models import Cave, Person, PersonExpedition, LogbookEntry, QM +from models import Cave, Person, PersonExpedition, LogbookEntry, QM, Expedition import django.forms as forms from django.forms.formsets import formset_factory from django.contrib.admin.widgets import AdminDateWidget @@ -86,3 +86,33 @@ def get_name(pe): return pe.nickname else: return pe.person.first_name + +class UploadFileForm(forms.Form): + title = forms.CharField(max_length=50) + file = forms.FileField() + html = forms.CharField(widget=TinyMCE(attrs={'cols': 80, 'rows': 30})) + lon_utm = forms.FloatField(required=False) + lat_utm = forms.FloatField(required=False) + slug = forms.CharField(max_length=50) + date = forms.DateField(required=False) + + caves = [cave.slug for cave in Cave.objects.all()] + caves.sort() + caves = ["-----"] + caves + cave = forms.ChoiceField([(c, c) for c in caves], required=False) + + entrance = forms.ChoiceField([("-----", "Please select a cave"), ], required=False) + qm = forms.ChoiceField([("-----", "Please select a cave"), ], required=False) + + expeditions = [e.year for e in Expedition.objects.all()] + expeditions.sort() + expeditions = ["-----"] + expeditions + expedition = forms.ChoiceField([(e, e) for e in expeditions], required=False) + + logbookentry = forms.ChoiceField([("-----", "Please select an expedition"), ], required=False) + + person = forms.ChoiceField([("-----", "Please select an expedition"), ], required=False) + + survey_point = forms.CharField() + + diff --git a/core/models.py b/core/models.py index 87f8ea9..f8e7400 100644 --- a/core/models.py +++ b/core/models.py @@ -174,7 +174,7 @@ class Person(TroggleModel): class PersonExpedition(TroggleModel): expedition = models.ForeignKey(Expedition) person = models.ForeignKey(Person) - + slugfield = models.SlugField(max_length=50,blank=True,null=True) is_guest = models.BooleanField(default=False) COMMITTEE_CHOICES = ( @@ -348,6 +348,7 @@ class CaveAndEntrance(TroggleModel): class Cave(TroggleModel): # too much here perhaps + slug = models.SlugField(max_length=50, unique = True) official_name = models.CharField(max_length=160) area = models.ManyToManyField(Area, blank=True, null=True) kataster_code = models.CharField(max_length=20,blank=True,null=True) @@ -367,7 +368,7 @@ class Cave(TroggleModel): extent = models.CharField(max_length=100,blank=True,null=True) survex_file = models.CharField(max_length=100,blank=True,null=True) description_file = models.CharField(max_length=200,blank=True,null=True) - + #class Meta: # unique_together = (("area", "kataster_number"), ("area", "unofficial_number")) # FIXME Kataster Areas and CUCC defined sub areas need seperating @@ -472,6 +473,7 @@ class SurveyStation(TroggleModel): return unicode(self.name) class Entrance(TroggleModel): + slug = models.SlugField(max_length=50, unique = True) name = models.CharField(max_length=100, blank=True,null=True) entrance_description = models.TextField(blank=True,null=True) explorers = models.TextField(blank=True,null=True) @@ -573,6 +575,9 @@ class QM(TroggleModel): #"Number","Grade","Area","Description","Page reference","Nearest station","Completion description","Comment" found_by = models.ForeignKey(LogbookEntry, related_name='QMs_found',blank=True, null=True ) ticked_off_by = models.ForeignKey(LogbookEntry, related_name='QMs_ticked_off',null=True,blank=True) + #cave = models.ForeignKey(Cave) + #expedition = models.ForeignKey(Expedition) + number = models.IntegerField(help_text="this is the sequential number in the year", ) GRADE_CHOICES=( ('A', 'A: Large obvious lead'), diff --git a/core/views_caves.py b/core/views_caves.py index 82d4b94..e24e6c2 100644 --- a/core/views_caves.py +++ b/core/views_caves.py @@ -78,4 +78,12 @@ def survey(request,year,wallet_number): def cave_description(request, cavedescription_name): cave_description = get_object_or_404(CaveDescription, short_name = cavedescription_name) - return render_with_context(request,'cave_description.html', locals()) \ No newline at end of file + return render_with_context(request,'cave_description.html', locals()) + +def get_entrances(request, caveslug): + cave = Cave.objects.get(slug = caveslug) + return render_with_context(request,'options.html', {"items": [(e.entrance.slug, e.entrance.slug) for e in cave.entrances()]}) + +def get_qms(request, caveslug): + cave = Cave.objects.get(slug = caveslug) + return render_with_context(request,'options.html', {"items": [(e.entrance.slug, e.entrance.slug) for e in cave.entrances()]}) diff --git a/core/views_logbooks.py b/core/views_logbooks.py index f9190c0..4495f03 100644 --- a/core/views_logbooks.py +++ b/core/views_logbooks.py @@ -241,4 +241,12 @@ def delLogbookEntry(lbe): pt.delete() lbe.delete() os.remove(lbe.filename) + +def get_people(request, expeditionslug): + exp = Expedition.objects.get(year = expeditionslug) + return render_with_context(request,'options.html', {"items": [(pe.slug, pe.name) for pe in exp.personexpedition_set.all()]}) + +def get_logbook_entries(request, expeditionslug): + exp = Expedition.objects.get(year = expeditionslug) + return render_with_context(request,'options.html', {"items": [(le.slug, "%s - %s" % (le.date, le.title)) for le in exp.logbookentry_set.all()]}) diff --git a/core/views_other.py b/core/views_other.py index 3acb87d..d840a30 100644 --- a/core/views_other.py +++ b/core/views_other.py @@ -1,4 +1,5 @@ from troggle.core.models import Cave, Expedition, Person, LogbookEntry, PersonExpedition, PersonTrip, DPhoto, QM +from troggle.core.forms import UploadFileForm from django.conf import settings from django import forms from django.template import loader, Context @@ -9,6 +10,7 @@ from django.http import HttpResponse, HttpResponseRedirect from django.core.urlresolvers import reverse from utils import render_with_context from core.models import * +from troggle.helper import login_required_if_public def showrequest(request): return HttpResponse(request.GET) @@ -204,4 +206,77 @@ def logbook_entry_suggestions(request): { 'unwiki_QMs':unwiki_QMs, 'any_suggestions':any_suggestions - }) \ No newline at end of file + }) + +@login_required_if_public +def newFile(request, pslug = None): +# if pslug: +# previousfile = LogbookEntry.objects.get(slug = pslug, date = previousdate, expedition = expedition) +# assert previousfile.filename + if request.method == 'POST': # If the form has been submitted... + tripForm = TripForm(request.POST) # A form bound to the POST data +# personTripFormSet = PersonTripFormSet(request.POST) +# if tripForm.is_valid() and personTripFormSet.is_valid(): # All validation rules pass +# dateStr = tripForm.cleaned_data["date"].strftime("%Y-%m-%d") +# directory = os.path.join(settings.EXPOWEB, +# "years", +# expedition.year, +# "autologbook") +# filename = os.path.join(directory, +# dateStr + "." + slugify(tripForm.cleaned_data["title"])[:50] + ".html") +# if not os.path.isdir(directory): +# os.mkdir(directory) +# if pslug and pdate: +# delLogbookEntry(previouslbe) +# f = open(filename, "w") +# template = loader.get_template('dataformat/logbookentry.html') +# context = Context({'trip': tripForm.cleaned_data, +# 'persons': personTripFormSet.cleaned_data, +# 'date': dateStr, +# 'expeditionyear': expeditionyear}) +# f.write(template.render(context)) +# f.close() +# print logbookparsers.parseAutoLogBookEntry(filename) +# return HttpResponseRedirect(reverse('expedition', args=[expedition.year])) # Redirect after POST + else: + if pslug: + pass +# if previouslbe.cave: +# tripForm = TripForm(initial={"date": previousdate, +# "title": previouslbe.title, +# "cave": previouslbe.cave.reference(), +# "location": None, +# "caveOrLocation": "cave", +# "html": previouslbe.text}) +# else: +# tripForm = TripForm(initial={"date": previousdate, +# "title": previouslbe.title, +# "cave": None, +# "location": previouslbe.place, +# "caveOrLocation": "location", +# "html": previouslbe.text}) +# personTripFormSet = PersonTripFormSet(initial=[{"name": get_name(py.personexpedition), +# "TU": py.time_underground, +# "author": py.is_logbook_entry_author} +# for py in previouslbe.persontrip_set.all()]) + else: + fileform = UploadFileForm() # An unbound form + + return render_with_context(request, 'editfile.html', { + 'fileForm': fileform, + + }) + +@login_required_if_public +def deleteFile(request, expeditionyear, date = None, slug = None): + expedition = Expedition.objects.get(year=expeditionyear) + previousdate = datetime.date(*[int(x) for x in date.split("-")]) + previouslbe = LogbookEntry.objects.get(slug = slug, date = previousdate, expedition = expedition) + delLogbookEntry(previouslbe) + return HttpResponseRedirect(reverse('expedition', args=[expedition.year])) # Redirect after POST + +def delFile(f): + for pt in lbe.persontrip_set.all(): + pt.delete() + lbe.delete() + os.remove(lbe.filename) diff --git a/flatpages/__init__.py b/flatpages/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/flatpages/models.py b/flatpages/models.py new file mode 100644 index 0000000..71a8362 --- /dev/null +++ b/flatpages/models.py @@ -0,0 +1,3 @@ +from django.db import models + +# Create your models here. diff --git a/flatpages/tests.py b/flatpages/tests.py new file mode 100644 index 0000000..2247054 --- /dev/null +++ b/flatpages/tests.py @@ -0,0 +1,23 @@ +""" +This file demonstrates two different styles of tests (one doctest and one +unittest). These will both pass when you run "manage.py test". + +Replace these with more appropriate tests for your application. +""" + +from django.test import TestCase + +class SimpleTest(TestCase): + def test_basic_addition(self): + """ + Tests that 1 + 1 always equals 2. + """ + self.failUnlessEqual(1 + 1, 2) + +__test__ = {"doctest": """ +Another way to test that 1 + 1 is equal to 2. + +>>> 1 + 1 == 2 +True +"""} + diff --git a/flatpages/views.py b/flatpages/views.py new file mode 100644 index 0000000..9c7483e --- /dev/null +++ b/flatpages/views.py @@ -0,0 +1,62 @@ +import troggle.settings as settings +from troggle.helper import login_required_if_public +from utils import render_with_context + +from django.http import HttpResponse, HttpResponseRedirect, Http404 +from django.core.urlresolvers import reverse +from django.template import Context, loader +import django.forms as forms +from tinymce.widgets import TinyMCE + +import os +import re + +def flatpage(request, path): + print path + if path.startswith("noinfo") and settings.PUBLIC_SITE and not request.user.is_authenticated(): + return HttpResponseRedirect(reverse("auth_login") + '?next=%s' % request.path) + try: + o = open(os.path.normpath(settings.EXPOWEB + path), "rb") + except IOError: + raise Http404 + if path.endswith(".htm") or path.endswith(".html"): + html = o.read() + m = re.search(r"(.*).*(.*)", html, re.DOTALL) + if m: + head, body = m.groups() + else: + return HttpResponse(html + "Page could not be split into header and body") + if re.search(r"iso-8859-1", html): + body = unicode(body, "iso-8859-1") + return render_with_context(request, 'flatpage.html', {'editable': True, 'path': path, 'head': head, 'body': body}) + else: + return HttpResponse(o.read()) + +@login_required_if_public +def editflatpage(request, path): + try: + filepath = os.path.normpath(settings.EXPOWEB + path) + o = open(filepath, "r") + except IOError: + raise Http404 + html = o.read() + m = re.search(r"(.*).*(.*)", html, re.DOTALL) + if m: + head, body = m.groups() + else: + return HttpResponse("Page could not be split into header and body") + if request.method == 'POST': # If the form has been submitted... + flatpageForm = FlatPageForm(request.POST) # A form bound to the POST data + if flatpageForm.is_valid():# Form valid therefore write file + f = open(filepath, "w") + template = loader.get_template('dataformat/flatfile.html') + context = Context({'form': flatpageForm.cleaned_data, 'head': head}) + f.write(template.render(context)) + f.close() + return HttpResponseRedirect(reverse('flatpage', args=[path])) # Redirect after POST + else: + flatpageForm = FlatPageForm({"html": body}) + return render_with_context(request, 'editflatpage.html', {'path': path, 'form': flatpageForm, }) + +class FlatPageForm(forms.Form): + html = forms.CharField(widget=TinyMCE(attrs={'cols': 80, 'rows': 30})) diff --git a/parsers/cavetab.py b/parsers/cavetab.py index 0fbde43..bf61d7f 100644 --- a/parsers/cavetab.py +++ b/parsers/cavetab.py @@ -103,7 +103,16 @@ def LoadCaveTab(): addToDefaultArgs(Extent, "extent") addToDefaultArgs(SurvexFile, "survex_file") addToDefaultArgs(Notes, "notes") - + if line[Area] == "1626": + if line[KatasterNumber] != "": + args["slug"] = line[Area] + "-" + line[KatasterNumber] + else: + args["slug"] = line[Area] + "-" + line[UnofficialNumber] + else: + if line[KatasterNumber] != "": + args["slug"] = "1623" + "-" + line[KatasterNumber] + else: + args["slug"] = "1623" + "-" + line[UnofficialNumber] #The following adds the legacy_file_path. This is always in either Autogen file or Link file for header in (AutogenFile,LinkFile): if line[header]: @@ -148,6 +157,12 @@ def LoadCaveTab(): line[MultipleEntrances] == 'entrance' or \ line[MultipleEntrances] == 'last entrance': args = {} + + if line[Entrances]: + entrance_letter = line[Entrances] + else: + entrance_letter = '' + def addToArgs(CSVname, modelName): if line[CSVname]: args[modelName] = html_to_wiki(line[CSVname]) @@ -201,15 +216,12 @@ def LoadCaveTab(): addToArgsSurveyStation(GPSpostSA, 'other_station') args['other_description'] = 'post selective availability GPS' addToArgs(Bearings, 'bearings') + args['slug'] = newCave.slug + entrance_letter newEntrance = models.Entrance(**args) newEntrance.save() logging.info("Added entrance "+str(newEntrance)+"\n") - - if line[Entrances]: - entrance_letter = line[Entrances] - else: - entrance_letter = '' + newCaveAndEntrance = models.CaveAndEntrance(cave = newCave, entrance = newEntrance, entrance_letter = entrance_letter) newCaveAndEntrance.save() diff --git a/templates/csrffaker.py b/templates/csrffaker.py deleted file mode 100644 index 86b1318..0000000 --- a/templates/csrffaker.py +++ /dev/null @@ -1,9 +0,0 @@ -import django -if django.VERSION[0] >=1 and django.VERSION[1] > 1: - pass -else: - from django import template - - register = template.Library() - @register.tag - def csrf_token(parser, token): return "" diff --git a/templates/dataformat/flatfile.html b/templates/dataformat/flatfile.html new file mode 100644 index 0000000..1ddb7a5 --- /dev/null +++ b/templates/dataformat/flatfile.html @@ -0,0 +1,10 @@ +{% autoescape off %} + + +{{ head }} + + +{{ form.html }} + + +{% endautoescape %} diff --git a/templates/editfile.html b/templates/editfile.html new file mode 100644 index 0000000..d3a29ec --- /dev/null +++ b/templates/editfile.html @@ -0,0 +1,96 @@ +{% extends "base.html" %} +{% load csrffaker %} +{% block title %}File{% endblock %} +{% block head %} + + + + + +{{ fileForm.media }} +{% endblock %} +{% block content %} + +
{% csrf_token %} + {{ fileForm.non_field_errors }} +
+ {{ fileForm.title.errors }} + + {{ fileForm.title }} +
+
+ {{ fileForm.slug.errors }} + + {{ fileForm.slug }} +
+
+ {{ fileForm.date.errors }} + + {{ fileForm.date }} +
+
+ {{ fileForm.lon_utm.errors }} + + {{ fileForm.lon_utm }} +
+
+ {{ fileForm.lat_utm.errors }} + + {{ fileForm.lat_utm }} +
+
+ {{ fileForm.cave.errors }} + + {{ fileForm.cave }} +
+
+ {{ fileForm.entrance.errors }} + + {{ fileForm.entrance }} +
+
+ {{ fileForm.qm.errors }} + + {{ fileForm.qm }} +
+
+ {{ fileForm.expedition.errors }} + + {{ fileForm.expedition }} +
+
+ {{ fileForm.logbookentry.errors }} + + {{ fileForm.logbookentry }} +
+
+ {{ fileForm.person.errors }} + + {{ fileForm.person }} +
+
+ {{ fileForm.html.errors }} + + {{ fileForm.html }} +
+

+
+ +{% endblock %} diff --git a/templates/editflatpage.html b/templates/editflatpage.html new file mode 100644 index 0000000..85a5bcc --- /dev/null +++ b/templates/editflatpage.html @@ -0,0 +1,12 @@ +{% extends "base.html" %} +{% block title %}Edit {{ path }}{% endblock %} +{% block head %} +{% load csrffaker %} + +{% endblock %} +{% block content %} +
{% csrf_token %} +{{form}} +

+
+{% endblock %} diff --git a/templates/flatpage.html b/templates/flatpage.html new file mode 100644 index 0000000..ef8c4ab --- /dev/null +++ b/templates/flatpage.html @@ -0,0 +1,9 @@ + + +{{ head|safe }} + + +{{ body|safe }} +{% if editable %}Edit{% endif %} + + diff --git a/templates/options.html b/templates/options.html new file mode 100644 index 0000000..b1d3d97 --- /dev/null +++ b/templates/options.html @@ -0,0 +1,3 @@ +{% for value, text in items %} + +{% endfor %} diff --git a/urls.py b/urls.py index c083c5b..3dc4bc2 100644 --- a/urls.py +++ b/urls.py @@ -36,6 +36,12 @@ actualurlpatterns = patterns('', url(r'^newlogbookentry/(?P.*)$', views_logbooks.newLogbookEntry, name="newLogBookEntry"), url(r'^editlogbookentry/(?P[^/]*)/(?P[^/]*)/(?P[^/]*)/$', views_logbooks.newLogbookEntry, name="editLogBookEntry"), url(r'^deletelogbookentry/(?P[^/]*)/(?P[^/]*)/(?P[^/]*)/$', views_logbooks.deleteLogbookEntry, name="deleteLogBookEntry"), + url(r'^newfile', views_other.newFile, name="newFile"), + + url(r'^getEntrances/(?P.*)', views_caves.get_entrances, name = "get_entrances"), + url(r'^getQMs/(?P.*)', views_caves.get_qms, name = "get_qms"), + url(r'^getPeople/(?P.*)', views_logbooks.get_people, name = "get_people"), + url(r'^getLogBookEntries/(?P.*)', views_logbooks.get_logbook_entries, name = "get_logbook_entries"), url(r'^cave/(?P[^/]+)/?$', views_caves.cave, name="cave"), url(r'^cavedescription/(?P[^/]+)/?$', views_caves.cave_description, name="cavedescription"), @@ -127,6 +133,9 @@ actualurlpatterns = patterns('', url(r'^experimental.*$', views_logbooks.experimental, name="experimental"), #url(r'^trip_report/?$',views_other.tripreport,name="trip_report") + + url(r'^(.*)_edit$', 'flatpages.views.editflatpage', name="editflatpage"), + url(r'^(.*)$', 'flatpages.views.flatpage', name="flatpage"), ) #Allow prefix to all urls