X-Git-Url: http://git.ithinksw.org/philo.git/blobdiff_plain/e85955f9021223d2d859d2b641d3b316e932e115..ee56a2ca0d6c5d08ee42a9452de4353e8f2643ba:/forms.py?ds=inline diff --git a/forms.py b/forms.py index 57e772d..b404f0d 100644 --- a/forms.py +++ b/forms.py @@ -1,13 +1,15 @@ from django import forms from django.contrib.admin.widgets import AdminTextareaWidget +from django.contrib.contenttypes.generic import BaseGenericInlineFormSet +from django.contrib.contenttypes.models import ContentType from django.core.exceptions import ValidationError, ObjectDoesNotExist +from django.db.models import Q from django.forms.models import model_to_dict, fields_for_model, ModelFormMetaclass, ModelForm, BaseInlineFormSet from django.forms.formsets import TOTAL_FORM_COUNT from django.template import loader, loader_tags, TemplateDoesNotExist, Context, Template as DjangoTemplate from django.utils.datastructures import SortedDict from philo.admin.widgets import ModelLookupWidget -from philo.models import Entity, Template, Contentlet, ContentReference -from philo.models.fields import RelationshipField +from philo.models import Entity, Template, Contentlet, ContentReference, Attribute, Node, NodeNavigationOverride from philo.utils import fattr @@ -19,6 +21,8 @@ def proxy_fields_for_entity_model(entity_model, fields=None, exclude=None, widge ignored = [] opts = entity_model._entity_meta for f in opts.proxy_fields: + if not f.editable: + continue if fields and not f.name in fields: continue if exclude and f.name in exclude: @@ -84,8 +88,12 @@ class EntityForm(EntityFormBase): # Would inherit from ModelForm directly if it instance = super(EntityForm, self).save(commit=False) for f in instance._entity_meta.proxy_fields: + if not f.editable or not f.name in cleaned_data: + continue if self._meta.fields and f.name not in self._meta.fields: continue + if self._meta.exclude and f.name in self._meta.exclude: + continue setattr(instance, f.attname, cleaned_data[f.name]) if commit: @@ -95,35 +103,67 @@ class EntityForm(EntityFormBase): # Would inherit from ModelForm directly if it return instance -def validate_template(template): - """ - Makes sure that the template and all included or extended templates are valid. - """ - for node in template.nodelist: - try: - if isinstance(node, loader_tags.ExtendsNode): - extended_template = node.get_parent(Context()) - validate_template(extended_template) - elif isinstance(node, loader_tags.IncludeNode): - included_template = loader.get_template(node.template_name.resolve(Context())) - validate_template(extended_template) - except Exception, e: - raise ValidationError("Template code invalid. Error was: %s: %s" % (e.__class__.__name__, e)) - - -class TemplateForm(ModelForm): - def clean_code(self): - code = self.cleaned_data['code'] - try: - t = DjangoTemplate(code) - except Exception, e: - raise ValidationError("Template code invalid. Error was: %s: %s" % (e.__class__.__name__, e)) +class AttributeForm(ModelForm): + def __init__(self, *args, **kwargs): + super(AttributeForm, self).__init__(*args, **kwargs) + + # This is necessary because model forms store changes to self.instance in their clean method. + # Mutter mutter. + self._cached_value_ct = self.instance.value_content_type + self._cached_value = self.instance.value + + if self.instance.value is not None: + value_field = self.instance.value.value_formfield() + if value_field: + self.fields['value'] = value_field + if hasattr(self.instance.value, 'content_type'): + self.fields['content_type'] = self.instance.value._meta.get_field('content_type').formfield(initial=getattr(self.instance.value.content_type, 'pk', None)) + + def save(self, *args, **kwargs): + # At this point, the cleaned_data has already been stored on self.instance. + if self.instance.value_content_type != self._cached_value_ct: + if self.instance.value is not None: + self._cached_value.delete() + if 'value' in self.cleaned_data: + del(self.cleaned_data['value']) + + if self.instance.value_content_type is not None: + # Make a blank value of the new type! Run special code for content_type attributes. + if hasattr(self.instance.value_content_type.model_class(), 'content_type'): + if self._cached_value and hasattr(self._cached_value, 'content_type'): + new_ct = self._cached_value.content_type + else: + new_ct = None + new_value = self.instance.value_content_type.model_class().objects.create(content_type=new_ct) + else: + new_value = self.instance.value_content_type.model_class().objects.create() + + new_value.apply_data(self.cleaned_data) + new_value.save() + self.instance.value = new_value + else: + # The value type is the same, but one of the fields has changed. + # Check to see if the changed value was the content type. We have to check the + # cleaned_data because self.instance.value.content_type was overridden. + if hasattr(self.instance.value, 'content_type') and 'content_type' in self.cleaned_data and 'value' in self.cleaned_data and (not hasattr(self._cached_value, 'content_type') or self._cached_value.content_type != self.cleaned_data['content_type']): + self.cleaned_data['value'] = None + + self.instance.value.apply_data(self.cleaned_data) + self.instance.value.save() + + super(AttributeForm, self).save(*args, **kwargs) + return self.instance + + class Meta: + model = Attribute - validate_template(t) - return code - class Meta: - model = Template +class AttributeInlineFormSet(BaseGenericInlineFormSet): + "Necessary to force the GenericInlineFormset to use the form's save method for new objects." + def save_new(self, form, commit): + setattr(form.instance, self.ct_field.get_attname(), ContentType.objects.get_for_model(self.instance).pk) + setattr(form.instance, self.ct_fk_field.get_attname(), self.instance.pk) + return form.save() class ContainerForm(ModelForm): @@ -133,14 +173,14 @@ class ContainerForm(ModelForm): class ContentletForm(ContainerForm): - content = forms.CharField(required=False, widget=AdminTextareaWidget) + content = forms.CharField(required=False, widget=AdminTextareaWidget, label='Content') def should_delete(self): return not bool(self.cleaned_data['content']) class Meta: model = Contentlet - fields = ['name', 'content', 'dynamic'] + fields = ['name', 'content'] class ContentReferenceForm(ContainerForm): @@ -162,8 +202,8 @@ class ContentReferenceForm(ContainerForm): class ContainerInlineFormSet(BaseInlineFormSet): def __init__(self, containers, data=None, files=None, instance=None, save_as_new=False, prefix=None, queryset=None): - # Unfortunately, I need to add some things to BaseInline between its __init__ and its super call, so - # a lot of this is repetition. + # Unfortunately, I need to add some things to BaseInline between its __init__ and its + # super call, so a lot of this is repetition. # Start cribbed from BaseInline from django.db.models.fields.related import RelatedObject @@ -280,7 +320,12 @@ class ContentReferenceInlineFormSet(ContainerInlineFormSet): super(ContentReferenceInlineFormSet, self).__init__(containers, data, files, instance, save_as_new, prefix, queryset) def get_container_instances(self, containers, qs): - qs = qs.filter(name__in=[c[0] for c in containers]) + filter = Q() + + for name, ct in containers: + filter |= Q(name=name, content_type=ct) + + qs = qs.filter(filter) container_instances = [] for container in qs: container_instances.append(container) @@ -292,4 +337,57 @@ class ContentReferenceInlineFormSet(ContainerInlineFormSet): name, content_type = self.extra_containers[i - self.initial_form_count() - 1] kwargs['instance'] = self.model(name=name, content_type=content_type) - return super(ContentReferenceInlineFormSet, self)._construct_form(i, **kwargs) \ No newline at end of file + return super(ContentReferenceInlineFormSet, self)._construct_form(i, **kwargs) + + +class NodeWithOverrideForm(forms.ModelForm): + title = NodeNavigationOverride._meta.get_field('title').formfield() + url = NodeNavigationOverride._meta.get_field('url').formfield() + child_navigation = NodeNavigationOverride._meta.get_field('child_navigation').formfield(required=False) + + def __init__(self, *args, **kwargs): + super(NodeWithOverrideForm, self).__init__(*args, **kwargs) + if self.instance.pk: + self._override = override = self.get_override(self.instance) + self.initial.update({ + 'title': override.title, + 'url': override.url, + 'child_navigation': override.child_navigation_json + }) + + def get_override(self, instance): + try: + return NodeNavigationOverride.objects.get(parent=self.instance.parent, child=self.instance) + except NodeNavigationOverride.DoesNotExist: + override = NodeNavigationOverride(parent=self.instance.parent, child=self.instance) + override.child_navigation = None + return override + + def save(self, commit=True): + obj = super(NodeWithOverrideForm, self).save(commit) + cleaned_data = self.cleaned_data + override = self.get_override(obj) + + # Override information should only be set if there was no previous override or if the + # information was just manually set - i.e. was not equal to the data on the cached override. + if not override.pk or cleaned_data['title'] != self._override.title or cleaned_data['url'] != self._override.url or cleaned_data['child_navigation'] != self._override.child_navigation: + override.title = self.cleaned_data['title'] + override.url = self.cleaned_data['url'] + override.child_navigation = self.cleaned_data['child_navigation'] + override.save() + return obj + + class Meta: + model = Node + + +class NodeOverrideInlineFormSet(BaseInlineFormSet): + def __init__(self, data=None, files=None, instance=None, save_as_new=False, prefix=None, queryset=None): + if queryset is None: + queryset = self.model._default_manager + queryset = queryset.filter(parent=instance, child__parent=instance) + super(NodeOverrideInlineFormSet, self).__init__(data, files, instance, save_as_new, prefix, queryset) + + def add_fields(self, form, index): + super(NodeOverrideInlineFormSet, self).add_fields(form, index) + form.fields['child'].queryset = self.instance.children.all() \ No newline at end of file