We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Show OrganisationIndicatorLabels belonging to all partners
The organisation with indicator labels defined, may not always be the primary organisation.  Currently, as an interim solution we display labels defined by all organisations. 

When there are multiple organizations with lots of labels (and possibly some of them very similar), this can turn out to be a problem. 

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `akvo/rsr/templatetags/project_editor.py`
Content:
```
1 # -*- coding: utf-8 -*-
2 
3 """Akvo RSR is covered by the GNU Affero General Public License.
4 
5 See more details in the license.txt file located at the root folder of the
6 Akvo RSR module. For additional details on the GNU license please
7 see < http://www.gnu.org/licenses/agpl.html >.
8 """
9 
10 from django import template
11 from django.db import models
12 from django.db.models import get_model, QuerySet
13 
14 from akvo.rsr.models import ProjectEditorValidation
15 
16 register = template.Library()
17 VALIDATION_CACHE = {}
18 
19 
20 def retrieve_model(obj):
21     """
22     Retrieves the model from 'obj', which can be either a Django Object or a string.
23     """
24     return get_model('rsr', obj.split('.')[0]) if isinstance(obj, basestring) else type(obj)
25 
26 
27 def retrieve_id(obj):
28     """
29     Retrieves the id from 'obj', which can be either a Django Object or a string.
30     """
31     if not isinstance(obj, basestring):
32         try:
33             return obj.id
34         except AttributeError:
35             return obj.project.id
36     else:
37         return "{0}_{1}".format(obj.split('.')[1], "new-0")
38 
39 
40 def get_validations():
41     """ Populate the VALIDATION_CACHE and return it."""
42 
43     if VALIDATION_CACHE.get('CACHE_VALID', False):
44         return VALIDATION_CACHE
45 
46     fields = ('validation', 'action', 'validation_set__pk')
47     for name, action, validation_set in ProjectEditorValidation.objects.values_list(*fields):
48         if action == ProjectEditorValidation.MANDATORY_ACTION:
49             action = 'mandatory'
50         elif action == ProjectEditorValidation.HIDDEN_ACTION:
51             action = 'hidden'
52 
53         names = name.split('||')
54         for name in names:
55             indication = VALIDATION_CACHE.get(name, '')
56             indication += ' {0}-{1} '.format(action, validation_set)
57 
58             if action == 'mandatory' and len(names) > 1:
59                 other_names = set(names) - set([name])
60                 for or_name in other_names:
61                     indication += 'mandatory-{0}-or-{1} '.format(
62                         validation_set, or_name.split('.')[1]
63                     )
64 
65             VALIDATION_CACHE[name] = indication.strip()
66 
67     VALIDATION_CACHE['CACHE_VALID'] = True
68 
69     return VALIDATION_CACHE
70 
71 
72 def invalidate_validation_cache():
73     global VALIDATION_CACHE
74     VALIDATION_CACHE = {}
75 
76     return VALIDATION_CACHE
77 
78 
79 @register.filter
80 def obj_id(obj):
81     """
82     Generates the field's ID for a given model's field.
83 
84     :returns "1234" or "1234_new-0"
85     """
86     return "{0}".format(retrieve_id(obj))
87 
88 
89 @register.filter
90 def field_id(obj, field):
91     """
92     Generates the field's ID for a given model's field.
93 
94     :returns "rsr_project.title.1234"
95     """
96     return "{0}.{1}.{2}".format(
97         retrieve_model(obj)._meta.db_table,
98         field,
99         retrieve_id(obj)
100     )
101 
102 
103 @register.filter
104 def field_class(obj, field):
105     """
106     Similar to field_id(), but without the ID and a - to separate the fields. This is needed to
107     identify the class of a typeahead field.
108 
109     :returns "rsr_relatedproject-related_project"
110     """
111     return "{0}-{1}".format(
112         retrieve_model(obj)._meta.db_table,
113         field
114     )
115 
116 
117 @register.filter
118 def field_class_id(obj, field):
119     """
120     Similar to field_id(), but without the ID and a - to separate the fields. This is needed to
121     identify the class of a typeahead field.
122 
123     :returns "rsr_relatedproject-related_project"
124     """
125     return "{0}-{1}-{2}".format(
126         retrieve_model(obj)._meta.db_table,
127         field,
128         retrieve_id(obj)
129     )
130 
131 
132 @register.filter
133 def field_name(obj, field):
134     """
135     Retrieves the field's name for a given model's field, and makes first character uppercase. Also
136     taking into account that 'IATI' should always be in uppercase.
137 
138     :returns "Project title"
139     """
140     def check_iati_in_name(name):
141         """Checks whether IATI is in the field name and capitalises that part."""
142         return name.replace('iati', 'IATI').replace('Iati', 'IATI')
143 
144     return check_iati_in_name(retrieve_model(obj)._meta.get_field(field).verbose_name.capitalize())
145 
146 
147 @register.filter
148 def field_model_name(obj):
149     """
150     Retrieves the field's model name, and makes first character uppercase.
151 
152     :returns "Related project"
153     """
154     return retrieve_model(obj)._meta.verbose_name.capitalize()
155 
156 
157 @register.filter
158 def help_text(obj, field):
159     """
160     Retrieves the help text for a given model's field.
161 
162     :returns "If you are reporting multiple levels of projects in RSR, you can specify whether
163     this is a core, sub, or lower sub activity here."
164     """
165     return retrieve_model(obj)._meta.get_field(field).help_text
166 
167 
168 @register.filter
169 def max_length(obj, field):
170     """
171     Retrieves the max length of a given model's field.
172 
173     :returns 100
174     """
175     return retrieve_model(obj)._meta.get_field(field).max_length
176 
177 
178 @register.filter
179 def value(obj, field):
180     """
181     Retrieves the value of a given object's field.
182 
183     In case the object is a string, the supplied model and field are retrieved, and
184     the default value of the field returned, or an empty string if no default is specified.
185 
186     In case the object is a Django object, the value of that object is retrieved.
187     If the object is a related object (e.g. ForeignKey), the primary key of the related object
188     is returned.
189 
190     :returns "Project title"
191     :returns 1234 (in case of related object)
192     """
193     if isinstance(obj, basestring):
194         return ''
195     else:
196         field_value = getattr(obj, field)
197         if hasattr(field_value, 'pk'):
198             return field_value.pk
199         elif hasattr(field_value, 'url'):
200             return field_value.url
201         elif field_value is True:
202             return '1'
203         elif field_value is False:
204             return '2'
205         elif field_value in [0, 0.]:
206             return '0'
207         else:
208             return field_value or ''
209 
210 
211 @register.filter
212 def choices(obj, field):
213     """
214     Retrieves the choices of a given object's field and the IDs of the choices
215 
216     :returns [((1, "Core Activity"), (2, "Sub Activity"), (3, "Lower Sub Activity")), [1, 2, 3]]
217     """
218 
219     def first_items_list(iterable):
220         return [item[0] for item in iterable]
221 
222     def values_list_of(model, *fields):
223         if isinstance(model, QuerySet):
224             objects = model
225         else:
226             objects = get_model('rsr', model).objects.all()
227         return objects.values_list(*fields)
228 
229     def choices_and_ids(model, *fields):
230         choices_list = values_list_of(model, *fields)
231         return [
232             choices_list,
233             first_items_list(choices_list)
234         ]
235 
236     model = retrieve_model(obj)
237     model_field = model._meta.get_field(field)
238 
239     if not isinstance(model_field, models.ForeignKey):
240         return [model_field.choices, first_items_list(model_field.choices)]
241 
242     elif isinstance(obj, get_model('rsr', 'BudgetItem')) or \
243             (isinstance(obj, basestring) and 'BudgetItem' in obj):
244         # The ForeignKey field on budget items is the budget item labels
245         return choices_and_ids('budgetitemlabel', 'id', 'label')
246 
247     elif isinstance(obj, get_model('rsr', 'ProjectLocation')) or \
248             (isinstance(obj, basestring) and 'ProjectLocation' in obj):
249         # The ForeignKey field on locations is the countries
250         return choices_and_ids('country', 'id', 'name')
251 
252     elif isinstance(obj, get_model('rsr', 'IndicatorLabel')) or \
253             (isinstance(obj, basestring) and 'IndicatorLabel' in obj):
254 
255         if isinstance(obj, basestring) and 'IndicatorLabel' in obj:
256             # String looking like: u'IndicatorLabel.5577_22634_19197', 5577 is the project ID
257             project_pk = obj.split('.')[1].split('_')[0]
258             project = get_model('rsr', 'Project').objects.get(pk=project_pk)
259         else:
260             project = obj.indicator.result.project
261         organisation_indicator_labels = get_model('rsr', 'OrganisationIndicatorLabel').objects.filter(
262             organisation=project.primary_organisation
263         )
264         return choices_and_ids(organisation_indicator_labels, 'id', 'label')
265 
266 
267 @register.filter
268 def manytomany_value(obj):
269     """
270     Retrieves the id of a given object's field.
271 
272     :returns ((1, "Akvo/Chum"), (2, "Yep"))
273     """
274     return '' if isinstance(obj, basestring) else obj.pk
275 
276 
277 @register.filter
278 def manytomany_choices(obj, field):
279     """
280     Retrieves the choices of a given object's Model. All objects of that Model should be displayed.
281 
282     :returns ((1, "Akvo/Chum"), (2, "Yep"))
283     """
284     return retrieve_model(obj).objects.all().values_list('id', field)
285 
286 
287 @register.filter
288 def mandatory_or_hidden(validations, field):
289     """
290     Retrieves the mandatory and hidden fields for project editor validations.
291 
292     :returns A string of the form mandatory-{validation ID} and/or hidden-{validation_ID}
293     """
294 
295     if '.' in field:
296         # Model fields like 'rsr_relatedproject.12.relation'
297         field_name_list = field.split('.')
298         new_field_name = '.'.join([field_name_list[0], field_name_list[1]])
299 
300     else:
301         # Full models like 'rsr_relatedproject'
302         new_field_name = field
303 
304     indication = get_validations().get(new_field_name, '')
305 
306     # XXX: Not sure why exactly 'rsr_project.current_image' needs to be special
307     # cased, but this code just retains the behavior of the older code.
308     if field == 'rsr_project.current_image':
309         indication = ' '.join(
310             filter(lambda x: not x.startswith('mandatory'), indication.split())
311         )
312 
313     return indication
314
```

Path: `akvo/rsr/models/organisation_indicator_label.py`
Content:
```
1 # -*- coding: utf-8 -*-
2 
3 # Akvo Reporting is covered by the GNU Affero General Public License.
4 # See more details in the license.txt file located at the root folder of the Akvo RSR module.
5 # For additional details on the GNU license please see < http://www.gnu.org/licenses/agpl.html >.
6 
7 
8 from django.db import models
9 from django.utils.translation import ugettext_lazy as _
10 
11 from ..fields import ValidXMLCharField
12 
13 
14 class OrganisationIndicatorLabel(models.Model):
15     from .organisation import Organisation
16 
17     organisation = models.ForeignKey(Organisation, verbose_name=_(u'organisation'),
18                                      related_name='indicator_labels')
19     label = ValidXMLCharField(_(u'label'), max_length=100)
20 
21     class Meta:
22         app_label = 'rsr'
23         verbose_name = _(u'organisation indicator label')
24         verbose_name_plural = _(u'organisation indicator labels')
25         unique_together = ('organisation', 'label')
26 
27     def __unicode__(self):
28         return self.label
29
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/akvo/rsr/models/organisation_indicator_label.py b/akvo/rsr/models/organisation_indicator_label.py
--- a/akvo/rsr/models/organisation_indicator_label.py
+++ b/akvo/rsr/models/organisation_indicator_label.py
@@ -23,6 +23,7 @@
         verbose_name = _(u'organisation indicator label')
         verbose_name_plural = _(u'organisation indicator labels')
         unique_together = ('organisation', 'label')
+        ordering = ('organisation', 'label')
 
     def __unicode__(self):
         return self.label
diff --git a/akvo/rsr/templatetags/project_editor.py b/akvo/rsr/templatetags/project_editor.py
--- a/akvo/rsr/templatetags/project_editor.py
+++ b/akvo/rsr/templatetags/project_editor.py
@@ -259,8 +259,8 @@
         else:
             project = obj.indicator.result.project
         organisation_indicator_labels = get_model('rsr', 'OrganisationIndicatorLabel').objects.filter(
-            organisation=project.primary_organisation
-        )
+            organisation=project.all_partners()
+        ).distinct()
         return choices_and_ids(organisation_indicator_labels, 'id', 'label')

{"golden_diff": "diff --git a/akvo/rsr/models/organisation_indicator_label.py b/akvo/rsr/models/organisation_indicator_label.py\n--- a/akvo/rsr/models/organisation_indicator_label.py\n+++ b/akvo/rsr/models/organisation_indicator_label.py\n@@ -23,6 +23,7 @@\n         verbose_name = _(u'organisation indicator label')\n         verbose_name_plural = _(u'organisation indicator labels')\n         unique_together = ('organisation', 'label')\n+        ordering = ('organisation', 'label')\n \n     def __unicode__(self):\n         return self.label\ndiff --git a/akvo/rsr/templatetags/project_editor.py b/akvo/rsr/templatetags/project_editor.py\n--- a/akvo/rsr/templatetags/project_editor.py\n+++ b/akvo/rsr/templatetags/project_editor.py\n@@ -259,8 +259,8 @@\n         else:\n             project = obj.indicator.result.project\n         organisation_indicator_labels = get_model('rsr', 'OrganisationIndicatorLabel').objects.filter(\n-            organisation=project.primary_organisation\n-        )\n+            organisation=project.all_partners()\n+        ).distinct()\n         return choices_and_ids(organisation_indicator_labels, 'id', 'label')\n", "issue": "Show OrganisationIndicatorLabels belonging to all partners\nThe organisation with indicator labels defined, may not always be the primary organisation.  Currently, as an interim solution we display labels defined by all organisations. \r\n\r\nWhen there are multiple organizations with lots of labels (and possibly some of them very similar), this can turn out to be a problem. \n", "before_files": [{"content": "# -*- coding: utf-8 -*-\n\n\"\"\"Akvo RSR is covered by the GNU Affero General Public License.\n\nSee more details in the license.txt file located at the root folder of the\nAkvo RSR module. For additional details on the GNU license please\nsee < http://www.gnu.org/licenses/agpl.html >.\n\"\"\"\n\nfrom django import template\nfrom django.db import models\nfrom django.db.models import get_model, QuerySet\n\nfrom akvo.rsr.models import ProjectEditorValidation\n\nregister = template.Library()\nVALIDATION_CACHE = {}\n\n\ndef retrieve_model(obj):\n    \"\"\"\n    Retrieves the model from 'obj', which can be either a Django Object or a string.\n    \"\"\"\n    return get_model('rsr', obj.split('.')[0]) if isinstance(obj, basestring) else type(obj)\n\n\ndef retrieve_id(obj):\n    \"\"\"\n    Retrieves the id from 'obj', which can be either a Django Object or a string.\n    \"\"\"\n    if not isinstance(obj, basestring):\n        try:\n            return obj.id\n        except AttributeError:\n            return obj.project.id\n    else:\n        return \"{0}_{1}\".format(obj.split('.')[1], \"new-0\")\n\n\ndef get_validations():\n    \"\"\" Populate the VALIDATION_CACHE and return it.\"\"\"\n\n    if VALIDATION_CACHE.get('CACHE_VALID', False):\n        return VALIDATION_CACHE\n\n    fields = ('validation', 'action', 'validation_set__pk')\n    for name, action, validation_set in ProjectEditorValidation.objects.values_list(*fields):\n        if action == ProjectEditorValidation.MANDATORY_ACTION:\n            action = 'mandatory'\n        elif action == ProjectEditorValidation.HIDDEN_ACTION:\n            action = 'hidden'\n\n        names = name.split('||')\n        for name in names:\n            indication = VALIDATION_CACHE.get(name, '')\n            indication += ' {0}-{1} '.format(action, validation_set)\n\n            if action == 'mandatory' and len(names) > 1:\n                other_names = set(names) - set([name])\n                for or_name in other_names:\n                    indication += 'mandatory-{0}-or-{1} '.format(\n                        validation_set, or_name.split('.')[1]\n                    )\n\n            VALIDATION_CACHE[name] = indication.strip()\n\n    VALIDATION_CACHE['CACHE_VALID'] = True\n\n    return VALIDATION_CACHE\n\n\ndef invalidate_validation_cache():\n    global VALIDATION_CACHE\n    VALIDATION_CACHE = {}\n\n    return VALIDATION_CACHE\n\n\n@register.filter\ndef obj_id(obj):\n    \"\"\"\n    Generates the field's ID for a given model's field.\n\n    :returns \"1234\" or \"1234_new-0\"\n    \"\"\"\n    return \"{0}\".format(retrieve_id(obj))\n\n\n@register.filter\ndef field_id(obj, field):\n    \"\"\"\n    Generates the field's ID for a given model's field.\n\n    :returns \"rsr_project.title.1234\"\n    \"\"\"\n    return \"{0}.{1}.{2}\".format(\n        retrieve_model(obj)._meta.db_table,\n        field,\n        retrieve_id(obj)\n    )\n\n\n@register.filter\ndef field_class(obj, field):\n    \"\"\"\n    Similar to field_id(), but without the ID and a - to separate the fields. This is needed to\n    identify the class of a typeahead field.\n\n    :returns \"rsr_relatedproject-related_project\"\n    \"\"\"\n    return \"{0}-{1}\".format(\n        retrieve_model(obj)._meta.db_table,\n        field\n    )\n\n\n@register.filter\ndef field_class_id(obj, field):\n    \"\"\"\n    Similar to field_id(), but without the ID and a - to separate the fields. This is needed to\n    identify the class of a typeahead field.\n\n    :returns \"rsr_relatedproject-related_project\"\n    \"\"\"\n    return \"{0}-{1}-{2}\".format(\n        retrieve_model(obj)._meta.db_table,\n        field,\n        retrieve_id(obj)\n    )\n\n\n@register.filter\ndef field_name(obj, field):\n    \"\"\"\n    Retrieves the field's name for a given model's field, and makes first character uppercase. Also\n    taking into account that 'IATI' should always be in uppercase.\n\n    :returns \"Project title\"\n    \"\"\"\n    def check_iati_in_name(name):\n        \"\"\"Checks whether IATI is in the field name and capitalises that part.\"\"\"\n        return name.replace('iati', 'IATI').replace('Iati', 'IATI')\n\n    return check_iati_in_name(retrieve_model(obj)._meta.get_field(field).verbose_name.capitalize())\n\n\n@register.filter\ndef field_model_name(obj):\n    \"\"\"\n    Retrieves the field's model name, and makes first character uppercase.\n\n    :returns \"Related project\"\n    \"\"\"\n    return retrieve_model(obj)._meta.verbose_name.capitalize()\n\n\n@register.filter\ndef help_text(obj, field):\n    \"\"\"\n    Retrieves the help text for a given model's field.\n\n    :returns \"If you are reporting multiple levels of projects in RSR, you can specify whether\n    this is a core, sub, or lower sub activity here.\"\n    \"\"\"\n    return retrieve_model(obj)._meta.get_field(field).help_text\n\n\n@register.filter\ndef max_length(obj, field):\n    \"\"\"\n    Retrieves the max length of a given model's field.\n\n    :returns 100\n    \"\"\"\n    return retrieve_model(obj)._meta.get_field(field).max_length\n\n\n@register.filter\ndef value(obj, field):\n    \"\"\"\n    Retrieves the value of a given object's field.\n\n    In case the object is a string, the supplied model and field are retrieved, and\n    the default value of the field returned, or an empty string if no default is specified.\n\n    In case the object is a Django object, the value of that object is retrieved.\n    If the object is a related object (e.g. ForeignKey), the primary key of the related object\n    is returned.\n\n    :returns \"Project title\"\n    :returns 1234 (in case of related object)\n    \"\"\"\n    if isinstance(obj, basestring):\n        return ''\n    else:\n        field_value = getattr(obj, field)\n        if hasattr(field_value, 'pk'):\n            return field_value.pk\n        elif hasattr(field_value, 'url'):\n            return field_value.url\n        elif field_value is True:\n            return '1'\n        elif field_value is False:\n            return '2'\n        elif field_value in [0, 0.]:\n            return '0'\n        else:\n            return field_value or ''\n\n\n@register.filter\ndef choices(obj, field):\n    \"\"\"\n    Retrieves the choices of a given object's field and the IDs of the choices\n\n    :returns [((1, \"Core Activity\"), (2, \"Sub Activity\"), (3, \"Lower Sub Activity\")), [1, 2, 3]]\n    \"\"\"\n\n    def first_items_list(iterable):\n        return [item[0] for item in iterable]\n\n    def values_list_of(model, *fields):\n        if isinstance(model, QuerySet):\n            objects = model\n        else:\n            objects = get_model('rsr', model).objects.all()\n        return objects.values_list(*fields)\n\n    def choices_and_ids(model, *fields):\n        choices_list = values_list_of(model, *fields)\n        return [\n            choices_list,\n            first_items_list(choices_list)\n        ]\n\n    model = retrieve_model(obj)\n    model_field = model._meta.get_field(field)\n\n    if not isinstance(model_field, models.ForeignKey):\n        return [model_field.choices, first_items_list(model_field.choices)]\n\n    elif isinstance(obj, get_model('rsr', 'BudgetItem')) or \\\n            (isinstance(obj, basestring) and 'BudgetItem' in obj):\n        # The ForeignKey field on budget items is the budget item labels\n        return choices_and_ids('budgetitemlabel', 'id', 'label')\n\n    elif isinstance(obj, get_model('rsr', 'ProjectLocation')) or \\\n            (isinstance(obj, basestring) and 'ProjectLocation' in obj):\n        # The ForeignKey field on locations is the countries\n        return choices_and_ids('country', 'id', 'name')\n\n    elif isinstance(obj, get_model('rsr', 'IndicatorLabel')) or \\\n            (isinstance(obj, basestring) and 'IndicatorLabel' in obj):\n\n        if isinstance(obj, basestring) and 'IndicatorLabel' in obj:\n            # String looking like: u'IndicatorLabel.5577_22634_19197', 5577 is the project ID\n            project_pk = obj.split('.')[1].split('_')[0]\n            project = get_model('rsr', 'Project').objects.get(pk=project_pk)\n        else:\n            project = obj.indicator.result.project\n        organisation_indicator_labels = get_model('rsr', 'OrganisationIndicatorLabel').objects.filter(\n            organisation=project.primary_organisation\n        )\n        return choices_and_ids(organisation_indicator_labels, 'id', 'label')\n\n\n@register.filter\ndef manytomany_value(obj):\n    \"\"\"\n    Retrieves the id of a given object's field.\n\n    :returns ((1, \"Akvo/Chum\"), (2, \"Yep\"))\n    \"\"\"\n    return '' if isinstance(obj, basestring) else obj.pk\n\n\n@register.filter\ndef manytomany_choices(obj, field):\n    \"\"\"\n    Retrieves the choices of a given object's Model. All objects of that Model should be displayed.\n\n    :returns ((1, \"Akvo/Chum\"), (2, \"Yep\"))\n    \"\"\"\n    return retrieve_model(obj).objects.all().values_list('id', field)\n\n\n@register.filter\ndef mandatory_or_hidden(validations, field):\n    \"\"\"\n    Retrieves the mandatory and hidden fields for project editor validations.\n\n    :returns A string of the form mandatory-{validation ID} and/or hidden-{validation_ID}\n    \"\"\"\n\n    if '.' in field:\n        # Model fields like 'rsr_relatedproject.12.relation'\n        field_name_list = field.split('.')\n        new_field_name = '.'.join([field_name_list[0], field_name_list[1]])\n\n    else:\n        # Full models like 'rsr_relatedproject'\n        new_field_name = field\n\n    indication = get_validations().get(new_field_name, '')\n\n    # XXX: Not sure why exactly 'rsr_project.current_image' needs to be special\n    # cased, but this code just retains the behavior of the older code.\n    if field == 'rsr_project.current_image':\n        indication = ' '.join(\n            filter(lambda x: not x.startswith('mandatory'), indication.split())\n        )\n\n    return indication\n", "path": "akvo/rsr/templatetags/project_editor.py"}, {"content": "# -*- coding: utf-8 -*-\n\n# Akvo Reporting is covered by the GNU Affero General Public License.\n# See more details in the license.txt file located at the root folder of the Akvo RSR module.\n# For additional details on the GNU license please see < http://www.gnu.org/licenses/agpl.html >.\n\n\nfrom django.db import models\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom ..fields import ValidXMLCharField\n\n\nclass OrganisationIndicatorLabel(models.Model):\n    from .organisation import Organisation\n\n    organisation = models.ForeignKey(Organisation, verbose_name=_(u'organisation'),\n                                     related_name='indicator_labels')\n    label = ValidXMLCharField(_(u'label'), max_length=100)\n\n    class Meta:\n        app_label = 'rsr'\n        verbose_name = _(u'organisation indicator label')\n        verbose_name_plural = _(u'organisation indicator labels')\n        unique_together = ('organisation', 'label')\n\n    def __unicode__(self):\n        return self.label\n", "path": "akvo/rsr/models/organisation_indicator_label.py"}], "after_files": [{"content": "# -*- coding: utf-8 -*-\n\n\"\"\"Akvo RSR is covered by the GNU Affero General Public License.\n\nSee more details in the license.txt file located at the root folder of the\nAkvo RSR module. For additional details on the GNU license please\nsee < http://www.gnu.org/licenses/agpl.html >.\n\"\"\"\n\nfrom django import template\nfrom django.db import models\nfrom django.db.models import get_model, QuerySet\n\nfrom akvo.rsr.models import ProjectEditorValidation\n\nregister = template.Library()\nVALIDATION_CACHE = {}\n\n\ndef retrieve_model(obj):\n    \"\"\"\n    Retrieves the model from 'obj', which can be either a Django Object or a string.\n    \"\"\"\n    return get_model('rsr', obj.split('.')[0]) if isinstance(obj, basestring) else type(obj)\n\n\ndef retrieve_id(obj):\n    \"\"\"\n    Retrieves the id from 'obj', which can be either a Django Object or a string.\n    \"\"\"\n    if not isinstance(obj, basestring):\n        try:\n            return obj.id\n        except AttributeError:\n            return obj.project.id\n    else:\n        return \"{0}_{1}\".format(obj.split('.')[1], \"new-0\")\n\n\ndef get_validations():\n    \"\"\" Populate the VALIDATION_CACHE and return it.\"\"\"\n\n    if VALIDATION_CACHE.get('CACHE_VALID', False):\n        return VALIDATION_CACHE\n\n    fields = ('validation', 'action', 'validation_set__pk')\n    for name, action, validation_set in ProjectEditorValidation.objects.values_list(*fields):\n        if action == ProjectEditorValidation.MANDATORY_ACTION:\n            action = 'mandatory'\n        elif action == ProjectEditorValidation.HIDDEN_ACTION:\n            action = 'hidden'\n\n        names = name.split('||')\n        for name in names:\n            indication = VALIDATION_CACHE.get(name, '')\n            indication += ' {0}-{1} '.format(action, validation_set)\n\n            if action == 'mandatory' and len(names) > 1:\n                other_names = set(names) - set([name])\n                for or_name in other_names:\n                    indication += 'mandatory-{0}-or-{1} '.format(\n                        validation_set, or_name.split('.')[1]\n                    )\n\n            VALIDATION_CACHE[name] = indication.strip()\n\n    VALIDATION_CACHE['CACHE_VALID'] = True\n\n    return VALIDATION_CACHE\n\n\ndef invalidate_validation_cache():\n    global VALIDATION_CACHE\n    VALIDATION_CACHE = {}\n\n    return VALIDATION_CACHE\n\n\n@register.filter\ndef obj_id(obj):\n    \"\"\"\n    Generates the field's ID for a given model's field.\n\n    :returns \"1234\" or \"1234_new-0\"\n    \"\"\"\n    return \"{0}\".format(retrieve_id(obj))\n\n\n@register.filter\ndef field_id(obj, field):\n    \"\"\"\n    Generates the field's ID for a given model's field.\n\n    :returns \"rsr_project.title.1234\"\n    \"\"\"\n    return \"{0}.{1}.{2}\".format(\n        retrieve_model(obj)._meta.db_table,\n        field,\n        retrieve_id(obj)\n    )\n\n\n@register.filter\ndef field_class(obj, field):\n    \"\"\"\n    Similar to field_id(), but without the ID and a - to separate the fields. This is needed to\n    identify the class of a typeahead field.\n\n    :returns \"rsr_relatedproject-related_project\"\n    \"\"\"\n    return \"{0}-{1}\".format(\n        retrieve_model(obj)._meta.db_table,\n        field\n    )\n\n\n@register.filter\ndef field_class_id(obj, field):\n    \"\"\"\n    Similar to field_id(), but without the ID and a - to separate the fields. This is needed to\n    identify the class of a typeahead field.\n\n    :returns \"rsr_relatedproject-related_project\"\n    \"\"\"\n    return \"{0}-{1}-{2}\".format(\n        retrieve_model(obj)._meta.db_table,\n        field,\n        retrieve_id(obj)\n    )\n\n\n@register.filter\ndef field_name(obj, field):\n    \"\"\"\n    Retrieves the field's name for a given model's field, and makes first character uppercase. Also\n    taking into account that 'IATI' should always be in uppercase.\n\n    :returns \"Project title\"\n    \"\"\"\n    def check_iati_in_name(name):\n        \"\"\"Checks whether IATI is in the field name and capitalises that part.\"\"\"\n        return name.replace('iati', 'IATI').replace('Iati', 'IATI')\n\n    return check_iati_in_name(retrieve_model(obj)._meta.get_field(field).verbose_name.capitalize())\n\n\n@register.filter\ndef field_model_name(obj):\n    \"\"\"\n    Retrieves the field's model name, and makes first character uppercase.\n\n    :returns \"Related project\"\n    \"\"\"\n    return retrieve_model(obj)._meta.verbose_name.capitalize()\n\n\n@register.filter\ndef help_text(obj, field):\n    \"\"\"\n    Retrieves the help text for a given model's field.\n\n    :returns \"If you are reporting multiple levels of projects in RSR, you can specify whether\n    this is a core, sub, or lower sub activity here.\"\n    \"\"\"\n    return retrieve_model(obj)._meta.get_field(field).help_text\n\n\n@register.filter\ndef max_length(obj, field):\n    \"\"\"\n    Retrieves the max length of a given model's field.\n\n    :returns 100\n    \"\"\"\n    return retrieve_model(obj)._meta.get_field(field).max_length\n\n\n@register.filter\ndef value(obj, field):\n    \"\"\"\n    Retrieves the value of a given object's field.\n\n    In case the object is a string, the supplied model and field are retrieved, and\n    the default value of the field returned, or an empty string if no default is specified.\n\n    In case the object is a Django object, the value of that object is retrieved.\n    If the object is a related object (e.g. ForeignKey), the primary key of the related object\n    is returned.\n\n    :returns \"Project title\"\n    :returns 1234 (in case of related object)\n    \"\"\"\n    if isinstance(obj, basestring):\n        return ''\n    else:\n        field_value = getattr(obj, field)\n        if hasattr(field_value, 'pk'):\n            return field_value.pk\n        elif hasattr(field_value, 'url'):\n            return field_value.url\n        elif field_value is True:\n            return '1'\n        elif field_value is False:\n            return '2'\n        elif field_value in [0, 0.]:\n            return '0'\n        else:\n            return field_value or ''\n\n\n@register.filter\ndef choices(obj, field):\n    \"\"\"\n    Retrieves the choices of a given object's field and the IDs of the choices\n\n    :returns [((1, \"Core Activity\"), (2, \"Sub Activity\"), (3, \"Lower Sub Activity\")), [1, 2, 3]]\n    \"\"\"\n\n    def first_items_list(iterable):\n        return [item[0] for item in iterable]\n\n    def values_list_of(model, *fields):\n        if isinstance(model, QuerySet):\n            objects = model\n        else:\n            objects = get_model('rsr', model).objects.all()\n        return objects.values_list(*fields)\n\n    def choices_and_ids(model, *fields):\n        choices_list = values_list_of(model, *fields)\n        return [\n            choices_list,\n            first_items_list(choices_list)\n        ]\n\n    model = retrieve_model(obj)\n    model_field = model._meta.get_field(field)\n\n    if not isinstance(model_field, models.ForeignKey):\n        return [model_field.choices, first_items_list(model_field.choices)]\n\n    elif isinstance(obj, get_model('rsr', 'BudgetItem')) or \\\n            (isinstance(obj, basestring) and 'BudgetItem' in obj):\n        # The ForeignKey field on budget items is the budget item labels\n        return choices_and_ids('budgetitemlabel', 'id', 'label')\n\n    elif isinstance(obj, get_model('rsr', 'ProjectLocation')) or \\\n            (isinstance(obj, basestring) and 'ProjectLocation' in obj):\n        # The ForeignKey field on locations is the countries\n        return choices_and_ids('country', 'id', 'name')\n\n    elif isinstance(obj, get_model('rsr', 'IndicatorLabel')) or \\\n            (isinstance(obj, basestring) and 'IndicatorLabel' in obj):\n\n        if isinstance(obj, basestring) and 'IndicatorLabel' in obj:\n            # String looking like: u'IndicatorLabel.5577_22634_19197', 5577 is the project ID\n            project_pk = obj.split('.')[1].split('_')[0]\n            project = get_model('rsr', 'Project').objects.get(pk=project_pk)\n        else:\n            project = obj.indicator.result.project\n        organisation_indicator_labels = get_model('rsr', 'OrganisationIndicatorLabel').objects.filter(\n            organisation=project.all_partners()\n        ).distinct()\n        return choices_and_ids(organisation_indicator_labels, 'id', 'label')\n\n\n@register.filter\ndef manytomany_value(obj):\n    \"\"\"\n    Retrieves the id of a given object's field.\n\n    :returns ((1, \"Akvo/Chum\"), (2, \"Yep\"))\n    \"\"\"\n    return '' if isinstance(obj, basestring) else obj.pk\n\n\n@register.filter\ndef manytomany_choices(obj, field):\n    \"\"\"\n    Retrieves the choices of a given object's Model. All objects of that Model should be displayed.\n\n    :returns ((1, \"Akvo/Chum\"), (2, \"Yep\"))\n    \"\"\"\n    return retrieve_model(obj).objects.all().values_list('id', field)\n\n\n@register.filter\ndef mandatory_or_hidden(validations, field):\n    \"\"\"\n    Retrieves the mandatory and hidden fields for project editor validations.\n\n    :returns A string of the form mandatory-{validation ID} and/or hidden-{validation_ID}\n    \"\"\"\n\n    if '.' in field:\n        # Model fields like 'rsr_relatedproject.12.relation'\n        field_name_list = field.split('.')\n        new_field_name = '.'.join([field_name_list[0], field_name_list[1]])\n\n    else:\n        # Full models like 'rsr_relatedproject'\n        new_field_name = field\n\n    indication = get_validations().get(new_field_name, '')\n\n    # XXX: Not sure why exactly 'rsr_project.current_image' needs to be special\n    # cased, but this code just retains the behavior of the older code.\n    if field == 'rsr_project.current_image':\n        indication = ' '.join(\n            filter(lambda x: not x.startswith('mandatory'), indication.split())\n        )\n\n    return indication\n", "path": "akvo/rsr/templatetags/project_editor.py"}, {"content": "# -*- coding: utf-8 -*-\n\n# Akvo Reporting is covered by the GNU Affero General Public License.\n# See more details in the license.txt file located at the root folder of the Akvo RSR module.\n# For additional details on the GNU license please see < http://www.gnu.org/licenses/agpl.html >.\n\n\nfrom django.db import models\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom ..fields import ValidXMLCharField\n\n\nclass OrganisationIndicatorLabel(models.Model):\n    from .organisation import Organisation\n\n    organisation = models.ForeignKey(Organisation, verbose_name=_(u'organisation'),\n                                     related_name='indicator_labels')\n    label = ValidXMLCharField(_(u'label'), max_length=100)\n\n    class Meta:\n        app_label = 'rsr'\n        verbose_name = _(u'organisation indicator label')\n        verbose_name_plural = _(u'organisation indicator labels')\n        unique_together = ('organisation', 'label')\n        ordering = ('organisation', 'label')\n\n    def __unicode__(self):\n        return self.label\n", "path": "akvo/rsr/models/organisation_indicator_label.py"}]}