2
0
mirror of https://expo.survex.com/repositories/troggle/.git synced 2024-11-21 23:01:52 +00:00

Added editing of flat pages. Added slugfields to models to refer to them.

This commit is contained in:
Martin Green 2011-06-02 19:16:16 +01:00
parent ede9e4a9bd
commit 50545af223
17 changed files with 376 additions and 20 deletions

View File

@ -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()

View File

@ -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'),

View File

@ -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())
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()]})

View File

@ -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()]})

View File

@ -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
})
})
@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)

0
flatpages/__init__.py Normal file
View File

3
flatpages/models.py Normal file
View File

@ -0,0 +1,3 @@
from django.db import models
# Create your models here.

23
flatpages/tests.py Normal file
View File

@ -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
"""}

62
flatpages/views.py Normal file
View File

@ -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"<head>(.*)</head>.*<body>(.*)</body>", 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"<head>(.*)</head>.*<body>(.*)</body>", 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}))

View File

@ -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()

View File

@ -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 ""

View File

@ -0,0 +1,10 @@
{% autoescape off %}
<html>
<head>
{{ head }}
</head>
<body>
{{ form.html }}
</body>
</html>
{% endautoescape %}

96
templates/editfile.html Normal file
View File

@ -0,0 +1,96 @@
{% extends "base.html" %}
{% load csrffaker %}
{% block title %}File{% endblock %}
{% block head %}
<script>
$(function() {
$("#id_date").datepicker({dateFormat: "yy-mm-dd"});
$("#id_cave").change(function() {
$('#id_entrance').load('{% url get_entrances caveslug="" %}' + this.value);
});
$("#id_cave").change(function() {
$('#id_qm').load('{% url get_qms caveslug="" %}' + this.value);
});
$("#id_expedition").change(function() {
$('#id_logbookentry').load('{% url get_logbook_entries expeditionslug="" %}' + this.value);
});
$("#id_expedition").change(function() {
$('#id_person').load('{% url get_people expeditionslug="" %}' + this.value);
});
});
</script>
<link rel="stylesheet" href="{{ settings.MEDIA_URL }}css/ui-lightness/jquery-ui-1.8.12.custom.css" type="text/css" media="all" />
<script src="{{ settings.MEDIA_URL }}js/jquery-ui-1.8.12.custom.min.js" type="text/javascript"></script>
<script src="{{ settings.MEDIA_URL }}js/jquery.formset.min.js" type="text/javascript"></script>
<script src="{{ settings.TINY_MCE_MEDIA_URL }}tiny_mce.js" type="text/javascript"></script>
{{ fileForm.media }}
{% endblock %}
{% block content %}
<form action="" method="post">{% csrf_token %}
{{ fileForm.non_field_errors }}
<div class="fieldWrapper">
{{ fileForm.title.errors }}
<label for="id_title">Title:</label>
{{ fileForm.title }}
</div>
<div class="fieldWrapper">
{{ fileForm.slug.errors }}
<label for="id_slug">Slug:</label>
{{ fileForm.slug }}
</div>
<div class="fieldWrapper">
{{ fileForm.date.errors }}
<label for="id_date">Date:</label>
{{ fileForm.date }}
</div>
<div class="fieldWrapper" id="lon_utm">
{{ fileForm.lon_utm.errors }}
<label for="id_lon_utm">Longitude:</label>
{{ fileForm.lon_utm }}
</div>
<div class="fieldWrapper" id="lat_utm">
{{ fileForm.lat_utm.errors }}
<label for="id_lat_utm">Latitude:</label>
{{ fileForm.lat_utm }}
</div>
<div class="fieldWrapper" id="cave">
{{ fileForm.cave.errors }}
<label for="id_cave">Cave:</label>
{{ fileForm.cave }}
</div>
<div class="fieldWrapper" id="entrance">
{{ fileForm.entrance.errors }}
<label for="id_entrance">Entrance:</label>
{{ fileForm.entrance }}
</div>
<div class="fieldWrapper" id="qm">
{{ fileForm.qm.errors }}
<label for="id_cavem">QM:</label>
{{ fileForm.qm }}
</div>
<div class="fieldWrapper" id="expedition">
{{ fileForm.expedition.errors }}
<label for="id_expediton">Expedition:</label>
{{ fileForm.expedition }}
</div>
<div class="fieldWrapper" id="logbookentry">
{{ fileForm.logbookentry.errors }}
<label for="id_logbookentry">Logbook Entry:</label>
{{ fileForm.logbookentry }}
</div>
<div class="fieldWrapper" id="person">
{{ fileForm.person.errors }}
<label for="id_expediton">Person:</label>
{{ fileForm.person }}
</div>
<div class="fieldWrapper">
{{ fileForm.html.errors }}
<label for="id_date">Content:</label>
{{ fileForm.html }}
</div>
<p><input type="submit" value="Sumbit Trip Report" /></p>
</form>
{% endblock %}

View File

@ -0,0 +1,12 @@
{% extends "base.html" %}
{% block title %}Edit {{ path }}{% endblock %}
{% block head %}
{% load csrffaker %}
<script src="{{ settings.TINY_MCE_MEDIA_URL }}tiny_mce.js" type="text/javascript"></script>
{% endblock %}
{% block content %}
<form action="" method="post">{% csrf_token %}
{{form}}
<p><input type="submit" value="Submit" /></p>
</form>
{% endblock %}

9
templates/flatpage.html Normal file
View File

@ -0,0 +1,9 @@
<html>
<head>
{{ head|safe }}
</head>
<body>
{{ body|safe }}
{% if editable %}<a href="{% url editflatpage path %}">Edit</a>{% endif %}
</body>
</html>

3
templates/options.html Normal file
View File

@ -0,0 +1,3 @@
{% for value, text in items %}
<option value="{{value}}">{{text}}</option>
{% endfor %}

View File

@ -36,6 +36,12 @@ actualurlpatterns = patterns('',
url(r'^newlogbookentry/(?P<expeditionyear>.*)$', views_logbooks.newLogbookEntry, name="newLogBookEntry"),
url(r'^editlogbookentry/(?P<expeditionyear>[^/]*)/(?P<pdate>[^/]*)/(?P<pslug>[^/]*)/$', views_logbooks.newLogbookEntry, name="editLogBookEntry"),
url(r'^deletelogbookentry/(?P<expeditionyear>[^/]*)/(?P<date>[^/]*)/(?P<slug>[^/]*)/$', views_logbooks.deleteLogbookEntry, name="deleteLogBookEntry"),
url(r'^newfile', views_other.newFile, name="newFile"),
url(r'^getEntrances/(?P<caveslug>.*)', views_caves.get_entrances, name = "get_entrances"),
url(r'^getQMs/(?P<caveslug>.*)', views_caves.get_qms, name = "get_qms"),
url(r'^getPeople/(?P<expeditionslug>.*)', views_logbooks.get_people, name = "get_people"),
url(r'^getLogBookEntries/(?P<expeditionslug>.*)', views_logbooks.get_logbook_entries, name = "get_logbook_entries"),
url(r'^cave/(?P<cave_id>[^/]+)/?$', views_caves.cave, name="cave"),
url(r'^cavedescription/(?P<cavedescription_name>[^/]+)/?$', 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