refactoring for view, add, edit, delete, save, and create

svn: r19609
This commit is contained in:
Doug Blank 2012-05-20 19:22:30 +00:00
parent 2fede54efb
commit 9e148614c6
5 changed files with 468 additions and 380 deletions

View File

@ -33,7 +33,10 @@
td.ColumnAttribute {
text-align: right;
}
{% ifequal action "edit" %}
#error {
color: red;
}
{% if action == "edit" or action == "add" %}
{% else %}
#rowspace {
height: 3px;
@ -42,7 +45,7 @@
border: 1px solid;
background-color: white;
}
{% endifequal %}
{% endif %}
</style
</head>

View File

@ -17,19 +17,15 @@
<div id="summaryarea">
<table class="infolist" style="width:90%;"> {% comment %} 5 cols {% endcomment %}
<tbody>
{% if user.is_authenticated %}
{% ifequal action "edit" %}
{% for error in personform.errors %}
Error in person: {{error}}<br>
<p id="error">Error in person: {{error}}</p>
{% endfor %}
{% for error in nameform.errors %}
Error in name: {{error}}<br>
<p id="error">Error in name: {{error}}</p>
{% endfor %}
{% for error in surnameform.errors %}
Error in surname: {{error}}<br>
<p id="error">Error in surname: {{error}}</p>
{% endfor %}
{% endifequal %}
{% endif %}
<form method="post">{% csrf_token %}
<tr>
<td colspan="4" id="subtitle">{{nameform|render_name:user}}</td>
@ -131,17 +127,23 @@
</div>
</div>
{% make_button "Back to People" "/person" %}
{% if user.is_superuser %}
{% ifequal action "edit" %}
{% if action == "edit" %}
{% make_button "Back to Person" "/person/%s" person.handle %}
<input type="hidden" name="action" value="save"/>
<input type="submit" value="Save"/>
{% else %}
{% make_button "Edit Person" "/person/%s/edit" person.handle %}
{% make_button "Add Person" "/person/add" %}
{% make_button "Delete Person" "/person/%s/delete" person.handle %}
{% endifequal %}
{% ifequal action "add" %}
{% make_button "Cancel" "/person/" %}
<input type="hidden" name="action" value="create"/>
<input type="submit" value="Add Person"/>
{% else %}
{% make_button "Back to People" "/person" %}
{% make_button "Add Person" "/person/add" %}
{% make_button "Edit Person" "/person/%s/edit" person.handle %}
{% make_button "Delete Person" "/person/%s/delete" person.handle %}
{% endifequal %}
{% endif %}
{% else %}
{% endif %}
</form>

View File

@ -101,12 +101,16 @@ def context_processor(request):
return context
def main_page(request):
"""
"""
context = RequestContext(request)
context["view"] = 'home'
context["tview"] = _('Home')
return render_to_response("main_page.html", context)
def logout_page(request):
"""
"""
context = RequestContext(request)
context["view"] = 'home'
context["tview"] = _('Home')
@ -117,12 +121,16 @@ def logout_page(request):
return HttpResponseRedirect('/')
def browse_page(request):
"""
"""
context = RequestContext(request)
context["view"] = 'browse'
context["tview"] = _('Browse')
return render_to_response('browse_page.html', context)
def user_page(request, username=None):
"""
"""
if request.user.is_authenticated():
if username is None:
profile = request.user.get_profile()
@ -139,31 +147,10 @@ def user_page(request, username=None):
else:
raise Http404(_("Requested page is not accessible."))
def fix_person(request, person):
try:
name = person.name_set.get(preferred=True)
except:
names = person.name_set.all().order_by("order")
if names.count() == 0:
name = Name(person=person,
surname_set=[Surname(surname="? Fixed")],
first_name="? Missing name",
preferred=True)
name.save()
else:
order = 1
for name in names:
if order == 1:
name.preferred = True
else:
name.preferred = False
name.order = order
name.save()
order += 1
if request:
return redirect("/person/%s" % person.handle)
def set_date(obj):
"""
Initial a date object to default.
"""
obj.calendar = 0
obj.modifier = 0
obj.quality = 0
@ -173,7 +160,7 @@ def set_date(obj):
obj.day1, obj.month1, obj.year1, obj.slash1 = 0, 0, 0, 0
obj.day2, obj.month2, obj.year2, obj.slash2 = 0, 0, 0, 0
def view_surname_detail(request, handle, order, sorder, action="view"):
def view_surname(request, handle, order, sorder, action="view"):
# /sdjhgsdjhdhgsd/name/1/surname/1 (view)
# /sdjhgsdjhdhgsd/name/1/surname/add
# /sdjhgsdjhdhgsd/name/1/surname/2/[edit|view|add|delete]
@ -203,10 +190,10 @@ def view_surname_detail(request, handle, order, sorder, action="view"):
context["form"] = form
context["order"] = name.order
context["sorder"] = sorder
view_template = 'view_surname_detail.html'
view_template = 'view_surname.html'
return render_to_response(view_template, context)
def view_name_detail(request, handle, order, action="view"):
def view_name(request, handle, order, action="view"):
if order == "add":
order = 0
action = "add"
@ -288,7 +275,7 @@ def view_name_detail(request, handle, order, action="view"):
context["form"] = form
context["order"] = name.order
context["next"] = "/person/%s/name/%d" % (person.handle, name.order)
view_template = "view_name_detail.html"
view_template = "view_name.html"
if action == "save":
context["action"] = "view"
return redirect("/person/%s/name/%d" % (person.handle, name.order))
@ -311,312 +298,83 @@ def send_file(request, filename, mimetype):
response['Content-Disposition'] = 'attachment; filename=%s' % base
return response
def process_action(request, view, handle, action):
def process_report_run(request, handle):
from webapp.reports import import_file, export_file, download
from cli.plug import run_report
import traceback
db = DbDjango()
if view == "report":
if request.user.is_authenticated():
profile = request.user.get_profile()
report = Report.objects.get(handle=handle)
if action == "run":
args = {"off": "pdf", "iff": "ged"} # basic defaults
# override from given defaults in table:
if report.options:
for pair in str(report.options).split(" "):
if "=" in pair:
key, value = pair.split("=", 1)
args[key] = value
# override from options on webpage:
if request.GET.has_key("options"):
options = str(request.GET.get("options"))
if options:
for pair in options.split(" "): # from webpage
if "=" in pair:
key, value = pair.split("=", 1)
args[key] = value
if report.report_type == "textreport":
filename = "/tmp/%s-%s.%s" % (str(profile.user.username), str(handle), args["off"])
run_report(db, handle, of=filename, **args)
mimetype = 'application/%s' % args["off"]
elif report.report_type == "export":
filename = "/tmp/%s-%s.%s" % (str(profile.user.username), str(handle), args["off"])
export_file(db, filename, cli.user.User()) # callback
mimetype = 'text/plain'
elif report.report_type == "import":
filename = download(args["i"], "/tmp/%s-%s.%s" % (str(profile.user.username),
str(handle),
args["iff"]))
if filename is not None:
if True: # run in background, with error handling
import threading
def background():
try:
import_file(db, filename, cli.user.User()) # callback
except:
message = "import_file failed: " + traceback.format_exc()
request.user.message_set.create(message = message)
threading.Thread(target=background).start()
message = "Your data is now being imported..."
if request.user.is_authenticated():
profile = request.user.get_profile()
report = Report.objects.get(handle=handle)
args = {"off": "pdf", "iff": "ged"} # basic defaults
# override from given defaults in table:
if report.options:
for pair in str(report.options).split(" "):
if "=" in pair:
key, value = pair.split("=", 1)
args[key] = value
# override from options on webpage:
if request.GET.has_key("options"):
options = str(request.GET.get("options"))
if options:
for pair in options.split(" "): # from webpage
if "=" in pair:
key, value = pair.split("=", 1)
args[key] = value
if report.report_type == "textreport":
filename = "/tmp/%s-%s.%s" % (str(profile.user.username), str(handle), args["off"])
run_report(db, handle, of=filename, **args)
mimetype = 'application/%s' % args["off"]
elif report.report_type == "export":
filename = "/tmp/%s-%s.%s" % (str(profile.user.username), str(handle), args["off"])
export_file(db, filename, cli.user.User()) # callback
mimetype = 'text/plain'
elif report.report_type == "import":
filename = download(args["i"], "/tmp/%s-%s.%s" % (str(profile.user.username),
str(handle),
args["iff"]))
if filename is not None:
if True: # run in background, with error handling
import threading
def background():
try:
import_file(db, filename, cli.user.User()) # callback
except:
message = "import_file failed: " + traceback.format_exc()
request.user.message_set.create(message = message)
return redirect("/report/")
else:
success = import_file(db, filename, cli.user.User()) # callback
if not success:
message = "Failed to load imported."
request.user.message_set.create(message = message)
return redirect("/report/")
else:
message = "No filename was provided or found."
request.user.message_set.create(message = message)
return redirect("/report/")
else:
message = "Invalid report type '%s'" % report.report_type
threading.Thread(target=background).start()
message = "Your data is now being imported..."
request.user.message_set.create(message = message)
return redirect("/report/")
if os.path.exists(filename):
return send_file(request, filename, mimetype)
else:
context = RequestContext(request)
message = "Failed: '%s' is not found" % filename
request.user.message_set.create(message=message)
success = import_file(db, filename, cli.user.User()) # callback
if not success:
message = "Failed to load imported."
request.user.message_set.create(message = message)
return redirect("/report/")
else:
message = "No filename was provided or found."
request.user.message_set.create(message = message)
return redirect("/report/")
else:
message = "Invalid report type '%s'" % report.report_type
request.user.message_set.create(message = message)
return redirect("/report/")
if os.path.exists(filename):
return send_file(request, filename, mimetype)
else:
context = RequestContext(request)
message = "Failed: '%s' is not found" % filename
request.user.message_set.create(message=message)
return redirect("/report/")
# If failure, just fail for now:
context = RequestContext(request)
#context["view"] = view
#context["handle"] = handle
#context["action"] = action
context["message"] = "You need to be logged in."
#context["message"] = filename
return render_to_response("process_action.html", context)
def view_detail(request, view, handle, action="view"):
context = RequestContext(request)
context["action"] = action
context["view"] = view
context["tview"] = _('Browse')
if view == "event":
try:
obj = Event.objects.get(handle=handle)
except:
raise Http404(_("Requested %s does not exist.") % view)
view_template = 'view_event_detail.html'
context["tview"] = _("Event")
context["tviews"] = _("Events")
elif view == "family":
try:
obj = Family.objects.get(handle=handle)
except:
raise Http404(_("Requested %s does not exist.") % view)
view_template = 'view_family_detail.html'
context["tview"] = _("Family")
context["tviews"] = _("Families")
elif view == "media":
try:
obj = Media.objects.get(handle=handle)
except:
raise Http404(_("Requested %s does not exist.") % view)
view_template = 'view_media_detail.html'
context["tview"] = _("Media")
context["tviews"] = _("Media")
elif view == "note":
try:
obj = Note.objects.get(handle=handle)
except:
raise Http404(_("Requested %s does not exist.") % view)
view_template = 'view_note_detail.html'
context["tview"] = _("Note")
context["tviews"] = _("Notes")
elif view == "person":
try:
obj = Person.objects.get(handle=handle)
except:
raise Http404(_("Requested %s does not exist.") % view)
return view_person_detail(request, view, handle, action)
elif view == "place":
try:
obj = Place.objects.get(handle=handle)
except:
raise Http404(_("Requested %s does not exist.") % view)
view_template = 'view_place_detail.html'
context["tview"] = _("Place")
context["tviews"] = _("Places")
elif view == "repository":
try:
obj = Repository.objects.get(handle=handle)
except:
raise Http404(_("Requested %s does not exist.") % view)
view_template = 'view_repository_detail.html'
context["tview"] = _("Repository")
context["tviews"] = _("Repositories")
elif view == "citation":
try:
obj = Citation.objects.get(handle=handle)
except:
raise Http404(_("Requested %s does not exist.") % view)
view_template = 'view_citation_detail.html'
context["tview"] = _("Citation")
context["tviews"] = _("Citations")
elif view == "source":
try:
obj = Source.objects.get(handle=handle)
except:
raise Http404(_("Requested %s does not exist.") % view)
view_template = 'view_source_detail.html'
context["tview"] = _("Source")
context["tviews"] = _("Sources")
elif view == "tag":
try:
obj = Tag.objects.get(handle=handle)
except:
raise Http404(_("Requested %s does not exist.") % view)
view_template = 'view_tag_detail.html'
context["tview"] = _("Tag")
context["tviews"] = _("Tags")
elif view == "report":
try:
obj = Report.objects.get(handle=handle)
except:
raise Http404(_("Requested %s does not exist.") % view)
view_template = 'view_report_detail.html'
context["tview"] = _("Report")
context["tviews"] = _("Reports")
else:
raise Http404(_("Requested page type not known"))
context[view] = obj
context["object"] = obj
context["next"] = "/%s/%s" % (view, obj.handle)
return render_to_response(view_template, context)
def view_person_detail(request, view, handle, action="view"):
context = RequestContext(request)
context["tview"] = _("Person")
context["tviews"] = _("People")
if handle == "add":
# FIXME: what should handle be then?
if request.POST.has_key("action"): # save
action = request.POST.get("action")
else:
action = "add"
elif request.POST.has_key("action"):
action = request.POST.get("action")
if request.user.is_authenticated():
if action == "edit":
pf, nf, sf, person = get_person_forms(handle, empty=True)
elif action == "add":
# make new data:
person = Person()
name = Name(person=person, preferred=True,
display_as=NameFormatType.objects.get(val=0),
sort_as=NameFormatType.objects.get(val=0),
name_type=NameType.objects.get(val=2))
nf = NameForm(instance=name)
nf.model = name
pf = PersonForm(instance=person)
pf.model = person
action = "edit"
elif action == "save":
try:
person = Person.objects.get(handle=handle)
except:
person = Person(handle=create_id())
if person.id: # editing
try:
name = person.name_set.get(preferred=True)
except:
name = Name(person=person, preferred=True)
name.save()
try:
surname = name.surname_set.get(primary=True)
except:
surname = Surname(name=name, primary=True)
else: # adding a new person with new name
name = Name(person=person, preferred=True)
surname = Surname(name=name, primary=True)
pf = PersonForm(request.POST, instance=person)
pf.model = person
nf = NameFormFromPerson(request.POST, instance=name)
nf.model = name
sf = SurnameForm(request.POST, instance=surname)
if nf.is_valid() and pf.is_valid() and sf.is_valid():
# name.preferred and surname.primary get set False in the above is_valid()
person = pf.save()
# Process data:
name = nf.save(commit=False)
# Manually set any data:
name.suffix = nf.cleaned_data["suffix"] if nf.cleaned_data["suffix"] != " suffix " else ""
name.preferred = True # FIXME: why is this False?
name.save()
# Process data:
surname = sf.save(commit=False)
# Manually set any data:
surname.prefix = sf.cleaned_data["prefix"] if sf.cleaned_data["prefix"] != " prefix " else ""
surname.primary = True # FIXME: why is this False?
surname.save()
# FIXME: last_saved, last_changed, last_changed_by
raw = dji.get_person(person)
person.cache = base64.encodestring(cPickle.dumps(raw))
person.save()
# FIXME: update probably_alive
return redirect("/person/%s" % person.handle)
else: # not valid, try again:
action = "edit"
else: # view
pf, nf, sf, person = get_person_forms(handle)
else: # view person detail
# BEGIN NON-AUTHENTICATED ACCESS
try:
person = Person.objects.get(handle=handle)
except:
raise Http404(_("Requested %s does not exist.") % view)
if person.private:
raise Http404(_("Requested %s is not accessible.") % view)
pf, nf, sf, person = get_person_forms(handle, protect=True)
# END NON-AUTHENTICATED ACCESS
context["action"] = action
context["view"] = view
context["tview"] = _("Person")
context["personform"] = pf
context["nameform"] = nf
context["surnameform"] = sf
context["person"] = person
context["object"] = person
context["next"] = "/person/%s" % person.handle
view_template = 'view_person_detail.html'
return render_to_response(view_template, context)
def get_person_forms(handle, protect=False, empty=False):
person = Person.objects.get(handle=handle)
try:
name = person.name_set.get(preferred=True)
except:
name = Name(person=person, preferred=True)
try:
surname = name.surname_set.get(primary=True)
except:
surname = Surname(name=name, primary=True)
if protect and person.probably_alive:
name.sanitize()
pf = PersonForm(instance=person)
pf.model = person
name.suffix = make_empty(empty, name.suffix, " suffix ")
nf = NameForm(instance=name)
nf.model = name
surname.prefix = make_empty(empty, surname.prefix, " prefix ")
sf = SurnameForm(instance=surname)
sf.model = surname
return pf, nf, sf, person
def make_empty(empty, value, empty_value):
if value:
return value
elif empty:
return empty_value
else:
return value
def view(request, view):
def view_list(request, view):
"""
"""
context = RequestContext(request)
search = ""
if view == "event":
@ -736,39 +494,19 @@ def view(request, view):
if request.user.is_authenticated():
if request.GET.has_key("search"):
search = request.GET.get("search")
if "," in search:
surname, first_name = [term.strip() for term in
search.split(",", 1)]
object_list = Name.objects \
.filter(Q(surname__surname__istartswith=surname,
first_name__istartswith=first_name)) \
.order_by("surname__surname", "first_name")
else:
object_list = Name.objects \
.filter((Q(surname__surname__icontains=search) |
Q(first_name__icontains=search) |
Q(suffix__icontains=search) |
Q(surname__prefix__icontains=search) |
Q(title__icontains=search) |
Q(person__gramps_id__icontains=search))
) \
.order_by("surname__surname", "first_name")
query = build_person_query(search, protect=False)
object_list = Name.objects \
.filter(query) \
.order_by("surname__surname", "first_name")
else:
object_list = Name.objects.all().order_by("surname__surname", "first_name")
else:
# BEGIN NON-AUTHENTICATED users
if request.GET.has_key("search"):
search = request.GET.get("search")
if "," in search:
search_text, trash = [term.strip() for term in search.split(",", 1)]
else:
search_text = search
query = build_person_query(search, protect=True)
object_list = Name.objects \
.select_related() \
.filter(Q(surname__surname__istartswith=search_text) &
Q(private=False) &
Q(person__private=False)
) \
.filter(query) \
.order_by("surname__surname", "first_name")
else:
object_list = Name.objects \
@ -918,3 +656,343 @@ def view(request, view):
else:
context["search_query"] = ""
return render_to_response(view_template, context)
def check_access(request, context, obj, action):
"""
Check to see if user has access to object. We don't need to
sanitize here, just check to see if we even acknowledge it exists.
"""
if request.user.is_authenticated():
if request.user.is_superuser:
return True
else:
return action in ["view"]
else: # outside viewer
return not obj.private
def action(request, view, handle, action):
"""
View a particular object given /object/handle (implied view),
/object/handle/action, or /object/add.
"""
# redirect:
rd = None
obj = None
context = RequestContext(request)
if request.POST.has_key("action"):
action = request.POST.get("action")
context["action"] = action
context["view"] = view
context["tview"] = _('Browse')
if view == "event":
try:
obj = Event.objects.get(handle=handle)
except:
raise Http404(_("Requested %s does not exist.") % view)
if not check_access(request, context, obj, action):
raise Http404(_("Requested %s does not exist.") % view)
view_template = 'view_event_detail.html'
rd = process_event(request, context, handle, action)
elif view == "family":
try:
obj = Family.objects.get(handle=handle)
except:
raise Http404(_("Requested %s does not exist.") % view)
view_template = 'view_family_detail.html'
rd = process_family(request, context, handle, action)
elif view == "media":
try:
obj = Media.objects.get(handle=handle)
except:
raise Http404(_("Requested %s does not exist.") % view)
view_template = 'view_media_detail.html'
rd = process_media(request, context, handle, action)
elif view == "note":
try:
obj = Note.objects.get(handle=handle)
except:
raise Http404(_("Requested %s does not exist.") % view)
view_template = 'view_note_detail.html'
rd = process_note(request, context, handle, action)
elif view == "person":
if action not in ["add", "create"]:
try:
obj = Person.objects.get(handle=handle)
except:
raise Http404(_("Requested %s does not exist.") % view)
view_template = 'view_person_detail.html'
rd = process_person(request, context, handle, action)
elif view == "place":
try:
obj = Place.objects.get(handle=handle)
except:
raise Http404(_("Requested %s does not exist.") % view)
view_template = 'view_place_detail.html'
rd = process_place(request, context, handle, action)
elif view == "repository":
try:
obj = Repository.objects.get(handle=handle)
except:
raise Http404(_("Requested %s does not exist.") % view)
view_template = 'view_repository_detail.html'
rd = process_repository(request, context, handle, action)
elif view == "citation":
try:
obj = Citation.objects.get(handle=handle)
except:
raise Http404(_("Requested %s does not exist.") % view)
view_template = 'view_citation_detail.html'
rd = process_citation(request, context, handle, action)
elif view == "source":
try:
obj = Source.objects.get(handle=handle)
except:
raise Http404(_("Requested %s does not exist.") % view)
view_template = 'view_source_detail.html'
rd = process_source(request, context, handle, action)
elif view == "tag":
try:
obj = Tag.objects.get(handle=handle)
except:
raise Http404(_("Requested %s does not exist.") % view)
view_template = 'view_tag_detail.html'
rd = process_tag(request, context, handle, action)
elif view == "report":
try:
obj = Report.objects.get(handle=handle)
except:
raise Http404(_("Requested %s does not exist.") % view)
view_template = 'view_report_detail.html'
rd = process_report(request, context, handle, action)
else:
raise Http404(_("Requested page type not known"))
if rd:
return rd
if obj:
context[view] = obj
context["object"] = obj
context["next"] = "/%s/%s" % (view, obj.handle)
return render_to_response(view_template, context)
def process_event(request, context, handle, action):
"""
Process action on event. Can return a redirect.
"""
context["tview"] = _("Event")
context["tviews"] = _("Events")
def process_family(request, context, handle, action):
"""
Process action on family. Can return a redirect.
"""
context["tview"] = _("Family")
context["tviews"] = _("Families")
def process_media(request, context, handle, action):
"""
Process action on media. Can return a redirect.
"""
context["tview"] = _("Media")
context["tviews"] = _("Media")
def process_note(request, context, handle, action):
"""
Process action on note. Can return a redirect.
"""
context["tview"] = _("Note")
context["tviews"] = _("Notes")
def process_place(request, context, handle, action):
"""
Process action on place. Can return a redirect.
"""
context["tview"] = _("Place")
context["tviews"] = _("Places")
def process_repository(request, context, handle, action):
"""
Process action on repository. Can return a redirect.
"""
context["tview"] = _("Repository")
context["tviews"] = _("Repositories")
def process_citation(request, context, handle, action):
"""
Process action on citation. Can return a redirect.
"""
context["tview"] = _("Citation")
context["tviews"] = _("Citations")
def process_source(request, context, handle, action):
"""
Process action on source. Can return a redirect.
"""
context["tview"] = _("Source")
context["tviews"] = _("Sources")
def process_tag(request, context, handle, action):
"""
Process action on tag. Can return a redirect.
"""
context["tview"] = _("Tag")
context["tviews"] = _("Tags")
def process_report(request, context, handle, action):
"""
Process action on report. Can return a redirect.
"""
if action == "run":
return process_report_run(request, handle)
context["tview"] = _("Report")
context["tviews"] = _("Reports")
def process_person(request, context, handle, action): # view, edit, save
"""
Process action on person. Can return a redirect.
"""
context["tview"] = _("Person")
context["tviews"] = _("People")
if request.user.is_authenticated():
if action in ["edit", "view"]:
pf, nf, sf, person = get_person_forms(handle, empty=False)
elif action == "add":
pf, nf, sf, person = get_person_forms(handle=None, protect=False, empty=True)
elif action == "delete":
pf, nf, sf, person = get_person_forms(handle, protect=False, empty=True)
person.delete()
return redirect("/person/")
elif action in ["save", "create"]: # could be create a new person
# look up old data, if any:
if handle:
person = Person.objects.get(handle=handle)
name = person.name_set.get(preferred=True)
surname = name.surname_set.get(primary=True)
else: # create new item
person = Person(handle=create_id())
name = Name(person=person, preferred=True)
surname = Surname(name=name, primary=True)
# combine with user data:
pf = PersonForm(request.POST, instance=person)
pf.model = person
nf = NameFormFromPerson(request.POST, instance=name)
nf.model = name
sf = SurnameForm(request.POST, instance=surname)
# check if valid:
if nf.is_valid() and pf.is_valid() and sf.is_valid():
# name.preferred and surname.primary get set False in the above is_valid()
person = pf.save()
# Process data:
name.person = person
name = nf.save(commit=False)
# Manually set any data:
name.suffix = nf.cleaned_data["suffix"] if nf.cleaned_data["suffix"] != " suffix " else ""
name.preferred = True # FIXME: why is this False?
name.save()
# Process data:
surname.name = name
surname = sf.save(commit=False)
# Manually set any data:
surname.prefix = sf.cleaned_data["prefix"] if sf.cleaned_data["prefix"] != " prefix " else ""
surname.primary = True # FIXME: why is this False?
surname.save()
# FIXME: last_saved, last_changed, last_changed_by
dji.rebuild_cache(person)
# FIXME: update probably_alive
return redirect("/person/%s" % person.handle)
else:
# need to edit again
if handle:
action = "edit"
else:
action = "add"
else: # error?
raise Http404(_("Requested %s does not exist.") % "person")
else: # not authenticated
# BEGIN NON-AUTHENTICATED ACCESS
try:
person = Person.objects.get(handle=handle)
except:
raise Http404(_("Requested %s does not exist.") % "person")
if person.private:
raise Http404(_("Requested %s does not exist.") % "person")
pf, nf, sf, person = get_person_forms(handle, protect=True)
# END NON-AUTHENTICATED ACCESS
context["action"] = action
context["view"] = "person"
context["tview"] = _("Person")
context["tviews"] = _("People")
context["personform"] = pf
context["nameform"] = nf
context["surnameform"] = sf
context["person"] = person
context["object"] = person
context["next"] = "/person/%s" % person.handle
def get_person_forms(handle, protect=False, empty=False):
if handle:
person = Person.objects.get(handle=handle)
else:
person = Person()
#person.gramps_id = "I0000" # FIXME: get next ID
## get a name
try:
name = person.name_set.get(preferred=True)
except:
name = Name(person=person, preferred=True,
display_as=NameFormatType.objects.get(val=0),
sort_as=NameFormatType.objects.get(val=0),
name_type=NameType.objects.get(val=2))
## get a surname
try:
surname = name.surname_set.get(primary=True)
except:
surname = Surname(name=name, primary=True)
if protect and person.probably_alive:
name.sanitize()
pf = PersonForm(instance=person)
pf.model = person
name.suffix = make_empty(empty, name.suffix, " suffix ")
nf = NameForm(instance=name)
nf.model = name
surname.prefix = make_empty(empty, surname.prefix, " prefix ")
sf = SurnameForm(instance=surname)
sf.model = surname
return pf, nf, sf, person
def make_empty(empty, value, empty_value):
if value:
return value
elif empty:
return empty_value
else:
return value
def boolean(s):
return s.lower() in ["true", "1", "yes", "y", "t"]
def build_person_query(search, protect):
if "," in search or "=" in search:
query = Q()
terms = ["surname", "given"]
for term in [term.strip() for term in search.split(",")]:
if "=" in term:
field, value = term.split("=")
else:
field = terms.pop(0)
value = term
if field == "surname":
query &= Q(surname__surname__istartswith=value)
elif field == "given":
query &= Q(first_name__istartswith=value)
elif field == "private":
query &= Q(person__private=boolean(value))
else:
query = (Q(surname__surname__icontains=search) |
Q(first_name__icontains=search) |
Q(suffix__icontains=search) |
Q(surname__prefix__icontains=search) |
Q(title__icontains=search) |
Q(person__gramps_id__icontains=search))
if protect:
query &= (Q(private=False) & Q(person__private=False))
return query

View File

@ -1467,7 +1467,7 @@ class DjangoInterface(object):
self.add_media_ref_list(event, media_list)
self.add_citation_list(event, citation_list)
def get_raw(item):
def get_raw(self, item):
"""
Build and return the raw, serialized data of an object.
"""
@ -1493,11 +1493,18 @@ class DjangoInterface(object):
raise Exception("Don't know how to get raw '%s'" % type(item))
return raw
def reset_cache(self, item):
"""
Resets the cache version of an object, but doesn't save it to the database.
"""
raw = self.get_raw(item)
item.cache = base64.encodestring(cPickle.dumps(raw))
def rebuild_cache(self, item):
"""
Reset the cache version of an object.
Resets the cache version of an object, and saves it to the database.
"""
raw = self.get_raw(ietm)
raw = self.get_raw(item)
item.cache = base64.encodestring(cPickle.dumps(raw))
item.save()

View File

@ -38,10 +38,7 @@ from django.conf.urls.defaults import *
from django.contrib import admin
admin.autodiscover()
from webapp.grampsdb.views import (main_page, user_page, logout_page,
process_action, view, view_detail,
view_name_detail, view_surname_detail,
browse_page)
from webapp.grampsdb.views import *
urlpatterns = patterns('',
# Specific matches first:
@ -64,23 +61,24 @@ urlpatterns += patterns('',
# The rest will match views:
urlpatterns += patterns('',
(r'^$', main_page),
(r'^favicon\.ico$', 'django.views.generic.simple.redirect_to',
{'url': '/styles/images/favicon.ico'}),
(r'^user/$', user_page),
(r'^user/(\w+)/$', user_page),
(r'^browse/$', browse_page),
(r'^login/$', 'django.contrib.auth.views.login'),
(r'^logout/$', logout_page),
(r'^(?P<view>(\w+))/$', view),
url(r'^person/(?P<handle>(\w+))/$', view_detail,
{"view": "person"}, name="view-person-detail"),
url(r'^person/(?P<handle>(\w+))/(?P<action>(\w+))$', view_detail,
{"view": "person"}, name="view-person-detail"),
(r'^(?P<view>(\w+))/(?P<handle>(\w+))/$', view_detail),
(r'^person/(?P<handle>(\w+))/name/(?P<order>(\w+))$', view_name_detail),
(r'^person/(?P<handle>(\w+))/name/(?P<order>(\w+))/(?P<action>(\w+))$', view_name_detail),
(r'^person/(?P<handle>(\w+))/name/(?P<order>(\w+))/surname/(?P<sorder>(\w+))$', view_surname_detail),
(r'^person/(?P<handle>(\w+))/name/(?P<order>(\w+))/surname/(?P<sorder>(\w+))/(?P<action>(\w+))$', view_surname_detail),
(r'^(?P<view>(\w+))/(?P<handle>(\w+))/(?P<action>(\w+))$', process_action),
(r'^favicon\.ico$', 'django.views.generic.simple.redirect_to', {'url': '/styles/images/favicon.ico'}),
(r'^(?P<view>(\w+))/$', view_list), # /object/
(r'^(?P<view>(\w+))/add$', action,
{"handle": None, "action": "add"}), # /object/add
(r'^(?P<view>(\w+))/(?P<handle>(\w+))/$', action,
{"action": "view"}), # /object/handle/
(r'^(?P<view>(\w+))/(?P<handle>(\w+))/(?P<action>(\w+))$',
action), # /object/handle/action
# (r'^person/(?P<handle>(\w+))/name/(?P<order>(\w+))$', view_name),
# (r'^person/(?P<handle>(\w+))/name/(?P<order>(\w+))/(?P<action>(\w+))$', view_name),
# (r'^person/(?P<handle>(\w+))/name/(?P<order>(\w+))/surname/(?P<sorder>(\w+))$', view_surname),
# (r'^person/(?P<handle>(\w+))/name/(?P<order>(\w+))/surname/(?P<sorder>(\w+))/(?P<action>(\w+))$', view_surname),
)
# In urls: