def clean_content(sender, instance, **kwargs): """Clean the PageContent objects for a given Page. New, needed PageContent objects will be created. Existing, needed PageContent objects will not be touched. Unneeded PageContent objects will be deleted. """ if kwargs.get('raw'): # We're in loaddata (or something similar). return page = instance fields = dict(stemplates.get_fields_bare(page.template)) current_contents = list(page.pagecontent_set.all()) for content in current_contents: if content.title not in fields or fields[content.title] != content.typ: content.delete() existing_contents = dict([(pc.title, pc.typ) for pc in page.pagecontent_set.all()]) for title, typ in fields.items(): if title not in existing_contents or existing_contents[title] != typ: PageContent(page=page, title=title, typ=typ, content='').save()
def save_model(self, request, obj, form, change): obj.save() if not form.ignore_content: # Use the authoritative list of fields, because browsers won't send along # boolean fields that are unchecked (False) at all. # This is ugly, but we have to do it. # # fields: list of (clean_field_title, field_type) pairs # fieldnames: list of clean_field_title # fieldtypes: dict of clean_field_title -> field_type pairs fields = [(clean_field_title(f[0]), f[1]) for f in stemplates.get_fields_bare(obj.template)] fieldnames = [f[0] for f in fields] fieldtypes = dict(fields) # content is going to be a dict of # clean_field_title -> cleaned data pairs # Default to 0, because browsers won't even send along a field for # a checkbox element that's unchecked. content = dict([(f, 0) for f in fieldnames]) # Now update content with the appropriate data from the form. for k, v in form.data.items(): if k.startswith('content_'): fieldname = k.split('_', 1)[1] fieldtype = fieldtypes[fieldname] if fieldtype == 'bool': v = 1 content[fieldname] = v for k, v in content.items(): pc = PageContent.objects.get(page=obj, cleaned_title=k) pc.content = v pc.save()