Skip to content

Commit

Permalink
Merge pull request #5 from Cadasta/json-attrs-view
Browse files Browse the repository at this point in the history
Adds JsonAttrsMixin
  • Loading branch information
ian-ross authored Jul 10, 2016
2 parents b387a9b + 285a83b commit fcfafa3
Show file tree
Hide file tree
Showing 2 changed files with 68 additions and 0 deletions.
16 changes: 16 additions & 0 deletions jsonattrs/mixins.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
from jsonattrs.models import Schema


class JsonAttrsMixin:
def get_context_data(self, *args, **kwargs):
context = super().get_context_data(*args, **kwargs)

obj = self.object
field = self.attributes_field
obj_attrs = getattr(obj, field)

schemas = Schema.objects.from_instance(obj)
attrs = [a for s in schemas for a in s.attributes.all()]
context[field] = [(a.long_name, obj_attrs.get(a.name, '—'))
for a in attrs if not a.omit]
return context
52 changes: 52 additions & 0 deletions tests/test_mixins.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
from django.test import TestCase
from django.views.generic import TemplateView

from django.contrib.contenttypes.models import ContentType
from jsonattrs import models, mixins

from . import factories


class JsonAttrsView(mixins.JsonAttrsMixin, TemplateView):
attributes_field = 'attrs'


class JsonAttrsMixinTest(TestCase):
def test_get_context(self):
models.create_attribute_types()
org = factories.OrganizationFactory.create()
project = factories.ProjectFactory.create(organization=org)
content_type = ContentType.objects.get(
app_label='tests', model='party')

schema1 = models.Schema.objects.create(
content_type=content_type,
selectors=(org.id, project.id))

models.Attribute.objects.create(
schema=schema1,
name='field_1',
long_name='Field 1',
attr_type=models.AttributeType.objects.get(name='text'),
index=0
)
models.Attribute.objects.create(
schema=schema1,
name='field_2',
long_name='Field 2',
attr_type=models.AttributeType.objects.get(name='text'),
index=1
)

party = factories.PartyFactory.create(
project=project,
attrs={'field_1': 'Some value'}
)

view = JsonAttrsView()
view.object = party
context = view.get_context_data()
assert len(context['attrs']) == 2

assert context['attrs'][0] == ('Field 1', 'Some value')
assert context['attrs'][1] == ('Field 2', '—')

0 comments on commit fcfafa3

Please sign in to comment.