django-pdfformfiller/views/api.py

104 lines
2.6 KiB
Python

import json
from django.http import HttpResponse
from django.utils.encoding import is_protected_type
from django.db.models.fields.files import File
from pdfformfiller import models
def json_response(data):
response = HttpResponse(json.dumps(data))
response['Content-Type'] = 'application/json'
return response
def extract_fields(model):
result = {}
for field in model._meta.fields:
value = result[field.name] = field._get_val_from_obj(model)
if isinstance(value, File):
value = value.url
result[field.name] = value
return result
"""
def pages(request, page_id=None):
context = {}
pages = []
if doc_id:
pages = models.Page.objects.get(pk = page_id)
elif request.GET('document', None):
doc_id = request.GET('document')
pages = models.Page.objects.filter(document__pk = doc_id)
else:
pages = []
for page in pages:
pages.append(extract_fields(page)) #, ['id', 'document', ))
context['pages'] = pages
return json_response(context)
def fields(request, page_id=None):
page = models.Page.objects.get(document__pk = pdf,
page_num = page_num)
fields = page.formfield_set.all()
context = {}
#context['page'] = extract_fields(page)
context['page']['fields'] = map(extract_fields, fields)
return json_response(context)
"""
def document(request):
documents = models.Document.objects.all().values('id','name')
return json_response(list(documents))
def document_detail(request, id):
document = models.Document.objects.get(pk=id)
context = extract_fields(document)
return json_response(context)
def page(request):
pages = models.Page.objects.all()
context = [extract_fields(p) for p in pages]
return json_response(context)
def page_detail(request, id):
page = models.Page.objects.get(pk=id)
context = extract_fields(page)
return json_response(context)
def document_pages(request, id):
pages = models.Page.objects.filter(document__pk=id)
context = [extract_fields(page) for page in pages]
return json_response(context)
def field(request):
fields = models.FormField.objects.all()
context = [extract_fields(f) for f in fields]
return json_response(context)
def field_detail(request, id):
field = models.FormField.objects.get(pk=id)
context = extract_fields(field)
return json_response(context)
def page_fields(request, id):
fields = models.FormField.objects.filter(page__pk=id)
context = [extract_fields(f) for f in fields]
return json_response(context)