import re from django import forms from django.conf import settings from django.urls import reverse from django.db.models import Q from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render from django.template import Context, loader import troggle.parsers.imports from troggle.core.models import Expedition, Person, PersonExpedition from troggle.core.models_caves import LogbookEntry, QM, Cave, PersonTrip from troggle.helper import login_required_if_public from troggle.core.forms import UploadFileForm print("** importing troggle/core/views_other.py") """Utility functions and code to serve the control panel and individual user's progress and task list (deprecated as we do not have individual user login). Also has code to download a logbook in a choice of formats (why?!) and to download all QMs (not working) """ def troggle404(request): # cannot get this to work. Handler404 in urls.py not right syntax '''Custom 404 page to be used even when Debug=True https://blog.juanwolf.fr/posts/programming/how-to-create-404-page-django/ ''' context = RequestContext(request) #context['caves'] = Cave.objects.all() return render(request, ('404.html', context.flatten())) def showrequest(request): return HttpResponse(request.GET) def frontpage(request): '''never seen in practice''' # bthe messages system does a popup on this page if there is a recent message, e.g. from the admin site actions. # via django.contrib.messages.middleware.MessageMiddleware # this is set in the templates. if request.user.is_authenticated(): return render(request,'tasks.html') expeditions = Expedition.objects.order_by("-year") logbookentry = LogbookEntry cave = Cave #from django.contrib.admin.templatetags import log return render(request,'frontpage.html', locals()) def controlPanel(request): jobs_completed=[] if request.method=='POST': if request.user.is_superuser: # NONE of this works now that databaseReset (now parsers.imports) has been so extensively rewritten reinit_db() import_caves() import_people() import_surveyscans() import_logbooks() import_QMs() import_tunnelfiles() import_survexblks() import_survexpos() else: if request.user.is_authenticated(): #The user is logged in, but is not a superuser. return render(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(request,'controlPanel.html', {'caves':Cave.objects.all(),'expeditions':Expedition.objects.all(),'jobs_completed':jobs_completed}) def downloadLogbook(request,year=None,extension=None,queryset=None): if year: current_expedition=Expedition.objects.get(year=year) logbook_entries=LogbookEntry.objects.filter(expedition=current_expedition) filename='logbook'+year elif queryset: logbook_entries=queryset filename='logbook' else: response = HttpResponse(content_type='text/plain') return response(r"Error: Logbook downloader doesn't know what year you want") if 'year' in request.GET: year=request.GET['year'] if 'extension' in request.GET: extension=request.GET['extension'] if extension =='txt': response = HttpResponse(content_type='text/plain') style='2008' elif extension == 'html': response = HttpResponse(content_type='text/html') style='2005' template='logbook'+style+'style.'+extension response['Content-Disposition'] = 'attachment; filename='+filename+'.'+extension t=loader.get_template(template) c=Context({'logbook_entries':logbook_entries}) response.write(t.render(c)) return response def downloadQMs(request): # Note to self: use get_cave method for the below if request.method=='GET': try: cave=Cave.objects.get(kataster_number=request.GET['cave_id']) except Cave.DoesNotExist: cave=Cave.objects.get(name=request.GET['cave_id']) from export import toqms response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename=qm.csv' toqms.writeQmTable(response,cave) return response def ajax_test(request): post_text = request.POST['post_data'] return HttpResponse("{'response_text': '"+post_text+" recieved.'}", content_type="application/json") def eyecandy(request): return def ajax_QM_number(request): res="" if request.method=='POST': cave=Cave.objects.get(id=request.POST['cave']) print(cave) exp=Expedition.objects.get(pk=request.POST['year']) print(exp) res=cave.new_QM_number(exp.year) return HttpResponse(res) print(" - newFile() is next in troggle/core/views_other.py") @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 else: fileform = UploadFileForm() # An unbound form return render(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) print("** Finished importing troggle/core/views_other.py")