SEBA-419 allow legacy to be specified on a per-model basis;
Deprecate "legacy" in favor of "custom_python"

Change-Id: I44625ff18ee7796996ae25ad700e58a0b36e7398
diff --git a/lib/xos-genx/xosgenx/targets/django.xtarget b/lib/xos-genx/xosgenx/targets/django.xtarget
index 1c06de3..081fb5f 100644
--- a/lib/xos-genx/xosgenx/targets/django.xtarget
+++ b/lib/xos-genx/xosgenx/targets/django.xtarget
@@ -1,22 +1,16 @@
-{%- if options.legacy =='"True"' -%}
+{% for m in proto.messages %}{% if not m.options.skip_django -%}
+{%- if xproto_list_evaluates_true([m.options.custom_python, m.options.legacy, options.custom_python, options.legacy]) -%}
 {%- set legacy_tag = '_decl' -%}
 {%- set legacy = True -%}
 {%- else -%}
 {%- set legacy_tag = '' -%}
 {%- set legacy = False -%}
 {%- endif -%}
-{% for m in proto.messages %}{% if not m.options.skip_django -%}
-{% if legacy %}
-{# handle models that use custom headers rather than deriving from xosbase #}
 {% if m.options.custom_header %}
 from {{ m.options.custom_header|replace('"','') }} import *
 {% else %}
 from core.models.xosbase import *
 {% endif %}
-{% else %}
-{% if file_exists(xproto_base_name(m.name)|lower+'_header.py') -%}from {{xproto_base_name(m.name)|lower }}_header import *{%- else -%}from header import *{% endif %}
-{% if file_exists(xproto_base_name(m.name)|lower+'_top.py') -%}{{ include_file(xproto_base_name(m.name)|lower+'_top.py') }} {% endif %}
-{% endif %}
 
 {%- for l in m.links %}
 
@@ -41,7 +35,7 @@
 {{ xproto_fol_to_python_validator(policy, proto.policies[policy], m, error) }}
 {% endfor %}
 
-class {{ m.name }}{{ legacy_tag }}{{ xproto_base_def(m.name, m.bases) }}:
+class {{ m.name }}_decl{{ xproto_base_def(m.name, m.bases) }}:
   plural_name = "{{ xproto_pluralize(m) }}"
 
   {%- set feedback_state_fields = xproto_optioned_fields_to_list(xproto_base_fields(m, proto.message_table) + m.fields, 'feedback_state', 'True')  %}
@@ -105,7 +99,7 @@
       {% for policy,error in xproto_validations(m.options) %}
       policy_{{policy}}_validator(self, None)
       {% endfor %}
-      super({{ m.name }}{{ legacy_tag }}, self).save(*args, **kwds)
+      super({{ m.name }}_decl, self).save(*args, **kwds)
 
   def can_access(self, ctx):
       {% if m.policy %}
@@ -117,6 +111,14 @@
       {% endif %}
       
   {% endif %}
-    
+
+{# To maintain compatibility with migrations, we need to ensure that both the _decl and the non-_decl model #}
+{# exist. So we automatically create all models as _decl, and then add these trivial stubs #}
+{% if not legacy %}
+class {{ m.name }}({{ m. name }}_decl):
+    class Meta:
+        proxy = True
+{% endif %}
+
 {% if file_exists(xproto_base_name(m.name)|lower+'_bottom.py') -%}{{ include_file(xproto_base_name(m.name)|lower+'_bottom.py') }}{% endif %}
 {% endif %}{% endfor %}