From 117e99511e0985701780ed1bcd3afd456e244ae3
     Added assertXML[Not]Equal assertions

To   015b1c15f25f2f72a40a9bfce9d91ec91ddff2a2
     Tests + revert firebug

----------------------- django/contrib/admin/options.py -----------------------
index f4205f2..58c55b0 100644
@@ -715,11 +715,16 @@ class ModelAdmin(BaseModelAdmin):
         """
         obj.delete()
 
-    def save_formset(self, request, form, formset, change):
+    def save_formset(self, request, formset, change):
         """
         Given an inline formset save it to the database.
         """
         formset.save()
+        for form in formset.forms:
+            if hasattr(form, 'nested_formsets'):
+                for nested_formset in form.nested_formsets:
+                    self.save_formset(request, nested_formset, change)
+                    
 
     def save_related(self, request, form, formsets, change):
         """
@@ -731,7 +736,7 @@ class ModelAdmin(BaseModelAdmin):
         """
         form.save_m2m()
         for formset in formsets:
-            self.save_formset(request, form, formset, change=change)
+            self.save_formset(request, formset, change=change)
 
     def render_change_form(self, request, context, add=False, change=False, form_url='', obj=None):
         opts = self.model._meta
@@ -920,6 +925,73 @@ class ModelAdmin(BaseModelAdmin):
             self.message_user(request, msg)
             return None
 
+    
+        
+    def add_nested_inline_formsets(self, request, inline, formset, depth=0):
+        if depth > 5:
+            raise Exception("Maximum nesting depth reached (5)")
+        for form in formset.forms:                
+            nested_formsets = []
+            for nested_inline in inline.get_inline_instances(request):
+                InlineFormSet = nested_inline.get_formset(request, form.instance)
+                prefix = "%s-%s" % (form.prefix, InlineFormSet.get_default_prefix())
+                if request.method == 'POST':
+                    nested_formset = InlineFormSet(request.POST, request.FILES, 
+                                                   instance=form.instance, 
+                                                   prefix=prefix, queryset=nested_inline.queryset(request))
+                else:
+                    nested_formset = InlineFormSet(instance=form.instance, 
+                                                   prefix=prefix, queryset=nested_inline.queryset(request))
+                nested_formsets.append(nested_formset)
+                if nested_inline.inlines:
+                    self.add_nested_inline_formsets(request, nested_inline, nested_formset, depth=depth+1)
+            form.nested_formsets = nested_formsets
+            
+    def wrap_nested_inline_formsets(self, request, inline, formset):
+        media = None
+        def get_media(extra_media):
+            if media:
+                return media + extra_media
+            else:
+                return extra_media
+                        
+        for form in formset.forms:
+            wrapped_nested_formsets = []
+            for nested_inline, nested_formset in zip(inline.get_inline_instances(request), form.nested_formsets):
+                if form.instance.pk:
+                    instance = form.instance
+                else:
+                    instance = None
+                fieldsets = list(nested_inline.get_fieldsets(request))
+                readonly = list(nested_inline.get_readonly_fields(request))
+                prepopulated = dict(nested_inline.get_prepopulated_fields(request))
+                wrapped_nested_formset = helpers.InlineAdminFormSet(nested_inline, nested_formset, 
+                                                             fieldsets, prepopulated, readonly, model_admin=self)
+                wrapped_nested_formsets.append(wrapped_nested_formset)
+                media = get_media(wrapped_nested_formset.media)
+                if nested_inline.inlines:
+                    media = get_media(self.wrap_nested_inline_formsets(request, nested_inline, nested_formset))
+            form.nested_formsets = wrapped_nested_formsets
+        return media
+    
+    def all_valid_with_nesting(self, formsets):
+        "Recursively validate all nested formsets"
+        if not all_valid(formsets):
+            return False
+        for formset in formsets:
+            if not formset.is_bound:
+                pass
+            for form in formset:
+                if hasattr(form, 'nested_formsets'):
+                    if not self.all_valid_with_nesting(form.nested_formsets):
+                        return False
+                    # Here be dragons :(
+                    if not form.cleaned_data:
+                        form._errors["__all__"] = form.error_class([u"Parent object must be created when creating nested inlines."])
+                        return False
+        return True
+            
+
     @csrf_protect_m
     @transaction.commit_on_success
     def add_view(self, request, form_url='', extra_context=None):
@@ -952,7 +1024,9 @@ class ModelAdmin(BaseModelAdmin):
                                   save_as_new="_saveasnew" in request.POST,
                                   prefix=prefix, queryset=inline.queryset(request))
                 formsets.append(formset)
-            if all_valid(formsets) and form_validated:
+                if inline.inlines:
+                    self.add_nested_inline_formsets(request, inline, formset)
+            if self.all_valid_with_nesting(formsets) and form_validated:
                 self.save_model(request, new_object, form, False)
                 self.save_related(request, form, formsets, False)
                 self.log_addition(request, new_object)
@@ -978,6 +1052,8 @@ class ModelAdmin(BaseModelAdmin):
                 formset = FormSet(instance=self.model(), prefix=prefix,
                                   queryset=inline.queryset(request))
                 formsets.append(formset)
+                if inline.inlines:
+                    self.add_nested_inline_formsets(request, inline, formset)
 
         adminForm = helpers.AdminForm(form, list(self.get_fieldsets(request)),
             self.get_prepopulated_fields(request),
@@ -994,6 +1070,8 @@ class ModelAdmin(BaseModelAdmin):
                 fieldsets, prepopulated, readonly, model_admin=self)
             inline_admin_formsets.append(inline_admin_formset)
             media = media + inline_admin_formset.media
+            if inline.inlines:
+                media = media + self.wrap_nested_inline_formsets(request, inline, formset)
 
         context = {
             'title': _('Add %s') % force_text(opts.verbose_name),
@@ -1047,10 +1125,11 @@ class ModelAdmin(BaseModelAdmin):
                 formset = FormSet(request.POST, request.FILES,
                                   instance=new_object, prefix=prefix,
                                   queryset=inline.queryset(request))
-
                 formsets.append(formset)
+                if inline.inlines:
+                    self.add_nested_inline_formsets(request, inline, formset)
 
-            if all_valid(formsets) and form_validated:
+            if self.all_valid_with_nesting(formsets) and form_validated:
                 self.save_model(request, new_object, form, True)
                 self.save_related(request, form, formsets, True)
                 change_message = self.construct_change_message(request, form, formsets)
@@ -1068,6 +1147,8 @@ class ModelAdmin(BaseModelAdmin):
                 formset = FormSet(instance=obj, prefix=prefix,
                                   queryset=inline.queryset(request))
                 formsets.append(formset)
+                if inline.inlines:
+                    self.add_nested_inline_formsets(request, inline, formset)
 
         adminForm = helpers.AdminForm(form, self.get_fieldsets(request, obj),
             self.get_prepopulated_fields(request, obj),
@@ -1084,6 +1165,8 @@ class ModelAdmin(BaseModelAdmin):
                 fieldsets, prepopulated, readonly, model_admin=self)
             inline_admin_formsets.append(inline_admin_formset)
             media = media + inline_admin_formset.media
+            if inline.inlines:
+                media = media + self.wrap_nested_inline_formsets(request, inline, formset)
 
         context = {
             'title': _('Change %s') % force_text(opts.verbose_name),
@@ -1358,6 +1441,7 @@ class InlineModelAdmin(BaseModelAdmin):
     verbose_name = None
     verbose_name_plural = None
     can_delete = True
+    inlines = []
 
     def __init__(self, parent_model, admin_site):
         self.admin_site = admin_site
@@ -1369,9 +1453,25 @@ class InlineModelAdmin(BaseModelAdmin):
         if self.verbose_name_plural is None:
             self.verbose_name_plural = self.model._meta.verbose_name_plural
 
+    def get_inline_instances(self, request):
+        inline_instances = []
+        for inline_class in self.inlines:
+            inline = inline_class(self.model, self.admin_site)
+            if request:
+                if not (inline.has_add_permission(request) or
+                        inline.has_change_permission(request) or
+                        inline.has_delete_permission(request)):
+                    continue
+                if not inline.has_add_permission(request):
+                    inline.max_num = 0
+            inline_instances.append(inline)
+        return inline_instances
+
     @property
     def media(self):
-        extra = '' if settings.DEBUG else '.min'
+        # FIXME: Development Handieness
+        # extra = '' if settings.DEBUG else '.min'
+        extra = ''
         js = ['jquery%s.js' % extra, 'jquery.init.js', 'inlines%s.js' % extra]
         if self.prepopulated_fields:
             js.extend(['urlify.js', 'prepopulate%s.js' % extra])

--------------- django/contrib/admin/static/admin/js/inlines.js ---------------
index 4dc9459..2c4fa6e 100644
@@ -32,15 +32,16 @@
         el.name = el.name.replace(id_regex, replacement);
       }
     };
-    var totalForms = $("#id_" + options.prefix + "-TOTAL_FORMS").attr("autocomplete", "off");
-    var nextIndex = parseInt(totalForms.val(), 10);
-    var maxForms = $("#id_" + options.prefix + "-MAX_NUM_FORMS").attr("autocomplete", "off");
-    // only show the add button if we are allowed to add more items,
-        // note that max_num = None translates to a blank string.
-    var showAddButton = maxForms.val() === '' || (maxForms.val()-totalForms.val()) > 0;
+    var nextIndex = get_no_forms(options.prefix);
+    
+    // Add form classes for dynamic behaviour
     $this.each(function(i) {
       $(this).not("." + options.emptyCssClass).addClass(options.formCssClass);
     });
+    
+    // Only show the add button if we are allowed to add more items,
+    // note that max_num = None translates to a blank string.
+    var showAddButton = get_max_forms(options.prefix) === '' || (get_max_forms(options.prefix)-get_no_forms(options.prefix)) > 0;
     if ($this.length && showAddButton) {
       var addButton;
       if ($this.attr("tagName") == "TR") {
@@ -56,7 +57,7 @@
       }
       addButton.click(function(e) {
         e.preventDefault();
-        var totalForms = $("#id_" + options.prefix + "-TOTAL_FORMS");
+        var nextIndex = get_no_forms(options.prefix);
         var template = $("#" + options.prefix + "-empty");
         var row = template.clone(true);
         row.removeClass(options.emptyCssClass)
@@ -76,49 +77,55 @@
           row.children(":first").append('<span><a class="' + options.deleteCssClass + '" href="javascript:void(0)">' + options.deleteText + "</a></span>");
         }
         row.find("*").each(function() {
-          updateElementIndex(this, options.prefix, totalForms.val());
+          updateElementIndex(this, options.prefix, nextIndex);
         });
+        // when adding something from a cloned formset the id is the same
+        
         // Insert the new form when it has been fully edited
         row.insertBefore($(template));
+        
+        // Insert the nested formsets into the new form
+        if (row.is("tr")) {
+          // If the forms are laid out in table rows, insert
+          // the remove button into the last table cell:
+          nested_formsets = create_nested_formset(options.prefix, nextIndex, options);
+          nested_formsets.each(function() {
+          	($('<tr class="nested-inline-row">').html(($('<td>', {colspan: '100%'}).html($(this))))).insertBefore($(template));
+          });
+        } else {
+        	// stacked
+          nested_formsets = create_nested_formset(options.prefix, nextIndex, options);
+          nested_formsets.each(function() {
+        	row.append($(this));
+          });
+        }
+        
         // Update number of total forms
-        $(totalForms).val(parseInt(totalForms.val(), 10) + 1);
-        nextIndex += 1;
+        change_no_forms(options.prefix, true);
+        
         // Hide add button in case we've hit the max, except we want to add infinitely
-        if ((maxForms.val() !== '') && (maxForms.val()-totalForms.val()) <= 0) {
+        if ((get_max_forms(options.prefix) !== '') && (get_max_forms(options.prefix)-get_no_forms(options.prefix)) <= 0) {
           addButton.parent().hide();
         }
+        
         // The delete button of each row triggers a bunch of other things
         row.find("a." + options.deleteCssClass).click(function(e) {
           e.preventDefault();
           // Remove the parent form containing this button:
           var row = $(this).parents("." + options.formCssClass);
+          var formset_to_update = row.parent();
           row.remove();
-          nextIndex -= 1;
+          change_no_forms(options.prefix, false);
           // If a post-delete callback was provided, call it with the deleted form:
           if (options.removed) {
-            options.removed(row);
-          }
-          // Update the TOTAL_FORMS form count.
-          var forms = $("." + options.formCssClass);
-          $("#id_" + options.prefix + "-TOTAL_FORMS").val(forms.length);
-          // Show add button again once we drop below max
-          if ((maxForms.val() === '') || (maxForms.val()-forms.length) > 0) {
-            addButton.parent().show();
-          }
-          // Also, update names and ids for all remaining form controls
-          // so they remain in sequence:
-          for (var i=0, formCount=forms.length; i<formCount; i++)
-          {
-            updateElementIndex($(forms).get(i), options.prefix, i);
-            $(forms.get(i)).find("*").each(function() {
-              updateElementIndex(this, options.prefix, i);
-            });
+            options.removed(formset_to_update);
           }
         });
         // If a post-add callback was supplied, call it with the added form:
         if (options.added) {
           options.added(row);
         }
+        nextIndex = nextIndex + 1;
       });
     }
     return this;
@@ -212,6 +219,13 @@
         var count = i + 1;
         $(this).html($(this).html().replace(/(#\d+)/g, "#" + count));
       });
+    };    
+
+    var update_inline_labels = function(formset_to_update) {
+      formset_to_update.children('.inline-related').not('.empty-form').children('h3').find('.inline_label').each(function(i) {
+        var count = i + 1;
+  		$(this).html($(this).html().replace(/(#\d+)/g, "#" + count));
+  	  });
     };
 
     var reinitDateTimeShortCuts = function() {
@@ -258,15 +272,164 @@
       deleteCssClass: "inline-deletelink",
       deleteText: options.deleteText,
       emptyCssClass: "empty-form",
-      removed: updateInlineLabel,
+      removed: update_inline_labels,
       added: (function(row) {
         initPrepopulatedFields(row);
         reinitDateTimeShortCuts();
         updateSelectFilter();
-        updateInlineLabel(row);
+        update_inline_labels(row.parent());
       })
     });
 
     return $rows;
   };
+  
+  function create_nested_formset(parent_formset_prefix, next_form_id, options) {
+  	var formsets = $(false);
+    // Normalize prefix to something we can rely on
+    var normalized_parent_formset_prefix = parent_formset_prefix.replace(/[-][0-9][-]/g,"-0-");
+    // Check if the form should have nested formsets
+    var nested_inlines = $('#' + normalized_parent_formset_prefix + "-group ." + normalized_parent_formset_prefix + "-nested-inline").not('.cloned');
+    nested_inlines.each(function() {
+      // prefixes for the nested formset
+      var normalized_formset_prefix = $(this).attr('id').split('-group')[0]; // = "parent_formset_prefix"-0-"nested_inline_name"_set
+      var formset_prefix = normalized_formset_prefix.replace(normalized_parent_formset_prefix + "-0", parent_formset_prefix + "-" + next_form_id); // = "parent_formset_prefix"-"next_form_id"-"nested_inline_name"_set
+      // Create the nested formset  
+      var nested_formsets = create_nested_formset(formset_prefix, 0, options);
+      // Find the normalized formset and clone it
+      var template = $("#" + normalized_formset_prefix + "-group").clone();
+      template.addClass('cloned');
+      if (template.children().first().hasClass('tabular')) {
+        // Template is tabular
+        template.find(".form-row").not(".empty-form").remove();
+        template.find(".nested-inline-row").remove();
+        // Make a new form
+        template_form = template.find("#" + normalized_formset_prefix + "-empty")
+        new_form = template_form.clone()
+                                .removeClass(options.emptyCssClass)
+                                .addClass(options.formCssClass);
+        new_form.insertBefore(template_form);
+        // Update Form Properties
+        template.find('#id_' + formset_prefix + '-TOTAL_FORMS').val(1);
+        update_props(template, normalized_formset_prefix, formset_prefix);
+        var add_text = template.find('.add-row').text();
+        template.find('.add-row').remove();
+        template.find('.tabular.inline-related tbody tr.' + formset_prefix + '-not-nested').tabularFormset({
+    		prefix: formset_prefix,
+    		adminStaticPrefix: options.adminStaticPrefix,
+    		addText: add_text,
+    		deleteText: options.deleteText
+  		});
+        // Insert nested formsets
+        nested_formsets.each(function() {
+          template.find("#" + formset_prefix + "-empty").before(($('<tr class="nested-inline-row">').html(($('<td>', {colspan: '100%'}).html($(this))))));
+        });
+      } else {
+        // Template is stacked
+        template.find(".inline-related").not(".empty-form").remove();
+        // Make a new form
+        template_form = template.find("#" + normalized_formset_prefix + "-empty")
+        new_form = template_form.clone()
+                                .removeClass(options.emptyCssClass)
+                                .addClass(options.formCssClass);
+        new_form.insertBefore(template_form);
+        // Update Form Properties
+        console.log('looking for: ' + '#id_' + formset_prefix + '-TOTAL_FORMS');
+        console.log(template.html());
+        template.find('#id_' + normalized_formset_prefix + '-TOTAL_FORMS').val(1);
+        new_form.find('.inline_label').text('#1');
+        update_props(template, normalized_formset_prefix, formset_prefix);
+        var add_text = template.find('.add-row').text();
+        template.find('.add-row').remove();
+        template.find(".inline-related").stackedFormset({
+    		prefix: formset_prefix,
+    		adminStaticPrefix: options.adminStaticPrefix,
+    		addText: add_text,
+    		deleteText: options.deleteText
+  		});
+        nested_formsets.each(function() {
+          new_form.append($(this));
+        });
+      }
+      if (formsets.length) {
+      	formsets = formsets.add(template);
+      } else {
+       	formsets = template;
+      }
+    });
+    return formsets;
+  };
+  
+  function update_props(template, normalized_formset_prefix, formset_prefix) {
+  	  // Fix template id
+  	  template.attr('id',template.attr('id').replace(normalized_formset_prefix, formset_prefix));
+  	  template.find('*').each(function() {
+	    if ($(this).attr("for")) {
+	      $(this).attr("for", $(this).attr("for").replace(normalized_formset_prefix, formset_prefix));
+	    }
+	    if ($(this).attr("class")) {
+	      $(this).attr("class", $(this).attr("class").replace(normalized_formset_prefix, formset_prefix));
+	    }
+	    if (this.id) {
+	      this.id = this.id.replace(normalized_formset_prefix, formset_prefix);
+	    }
+	    if (this.name) {
+	      this.name = this.name.replace(normalized_formset_prefix, formset_prefix);
+	    }
+  	  });
+  	  // fix __prefix__ where needed
+      prefix_fix = template.find(".inline-related").first();
+      nextIndex = get_no_forms(formset_prefix);
+      if (prefix_fix.hasClass('tabular')) {
+      	// tabular
+      	prefix_fix = prefix_fix.find('.form-row').first();
+      	prefix_fix.attr('id',prefix_fix.attr('id').replace('-empty','-' + nextIndex));
+      } else {
+      	// stacked
+      	prefix_fix.attr('id',prefix_fix.attr('id').replace('-empty','-' + nextIndex));
+      }
+      prefix_fix.find('*').each(function() {
+	    if ($(this).attr("for")) {
+	      $(this).attr("for", $(this).attr("for").replace('__prefix__', '0'));
+	    }
+	    if ($(this).attr("class")) {
+	      $(this).attr("class", $(this).attr("class").replace('__prefix__', '0'));
+	    }
+	    if (this.id) {
+	      this.id = this.id.replace('__prefix__', '0');
+	    }
+	    if (this.name) {
+	      this.name = this.name.replace('__prefix__', '0');
+	    }
+      });
+  };
+  
+  // This returns the amount of forms in the given formset
+  function get_no_forms(formset_prefix) {
+  	formset_prop = $("#id_" + formset_prefix + "-TOTAL_FORMS")
+  	if (!formset_prop.length) {
+  		return 0;
+  	}
+  	return parseInt(formset_prop.attr("autocomplete", "off").val());
+  }
+  
+  function change_no_forms(formset_prefix, increase) {
+  	var no_forms = get_no_forms(formset_prefix);
+  	if (increase) {
+  	  $("#id_" + formset_prefix + "-TOTAL_FORMS").attr("autocomplete", "off").val(parseInt(no_forms) + 1);
+  	} else {
+  	  $("#id_" + formset_prefix + "-TOTAL_FORMS").attr("autocomplete", "off").val(parseInt(no_forms) - 1);
+  	}
+  };
+  
+  // This return the maximum amount of forms in the given formset
+  function get_max_forms(formset_prefix) {
+  	var max_forms = $("#id_" + formset_prefix + "-MAX_FORMS").attr("autocomplete", "off").val();
+  	if (typeof max_forms == 'undefined') {
+  		return '';
+  	}
+  	return parseInt(max_forms);
+  	
+  };
+  
 })(django.jQuery);

-------- django/contrib/admin/templates/admin/edit_inline/stacked.html --------
index 2025dd8..91eb4b6 100644
@@ -1,13 +1,14 @@
 {% load i18n admin_static %}
-<div class="inline-group" id="{{ inline_admin_formset.formset.prefix }}-group">
-  <h2>{{ inline_admin_formset.opts.verbose_name_plural|title }}</h2>
-{{ inline_admin_formset.formset.management_form }}
-{{ inline_admin_formset.formset.non_form_errors }}
+{% with recursive_formset=inline_admin_formset stacked_template='admin/edit_inline/stacked.html' tabular_template='admin/edit_inline/tabular.html'%}
+<div class="inline-group {{ prev_prefix|default:"Root" }}-nested-inline" id="{{ recursive_formset.formset.prefix }}-group" style="margin-left: {{ indent|default:0 }}px">
+  <h2>{{ recursive_formset.opts.verbose_name_plural|title }}</h2>
+{{ recursive_formset.formset.management_form }}
+{{ recursive_formset.formset.non_form_errors }}
 
-{% for inline_admin_form in inline_admin_formset %}<div class="inline-related{% if forloop.last %} empty-form last-related{% endif %}" id="{{ inline_admin_formset.formset.prefix }}-{% if not forloop.last %}{{ forloop.counter0 }}{% else %}empty{% endif %}">
-  <h3><b>{{ inline_admin_formset.opts.verbose_name|title }}:</b>&nbsp;<span class="inline_label">{% if inline_admin_form.original %}{{ inline_admin_form.original }}{% else %}#{{ forloop.counter }}{% endif %}</span>
+{% for inline_admin_form in recursive_formset %}<div class="inline-related{% if forloop.last %} empty-form last-related{% endif %}" id="{{ recursive_formset.formset.prefix }}-{% if not forloop.last %}{{ forloop.counter0 }}{% else %}empty{% endif %}">
+  <h3><b>{{ recursive_formset.opts.verbose_name|title }}:</b>&nbsp;<span class="inline_label">{% if inline_admin_form.original %}{{ inline_admin_form.original }}{% else %}#{{ forloop.counter }}{% endif %}</span>
     {% if inline_admin_form.show_url %}<a href="{% url 'admin:view_on_site' inline_admin_form.original_content_type_id inline_admin_form.original.pk %}">{% trans "View on site" %}</a>{% endif %}
-    {% if inline_admin_formset.formset.can_delete and inline_admin_form.original %}<span class="delete">{{ inline_admin_form.deletion_field.field }} {{ inline_admin_form.deletion_field.label_tag }}</span>{% endif %}
+    {% if recursive_formset.formset.can_delete and inline_admin_form.original %}<span class="delete">{{ inline_admin_form.deletion_field.field }} {{ inline_admin_form.deletion_field.label_tag }}</span>{% endif %}
   </h3>
   {% if inline_admin_form.form.non_field_errors %}{{ inline_admin_form.form.non_field_errors }}{% endif %}
   {% for fieldset in inline_admin_form %}
@@ -15,16 +16,26 @@
   {% endfor %}
   {% if inline_admin_form.has_auto_field %}{{ inline_admin_form.pk_field.field }}{% endif %}
   {{ inline_admin_form.fk_field.field }}
+  {% if inline_admin_form.form.nested_formsets %}
+    {% for inline_admin_formset in inline_admin_form.form.nested_formsets %}
+   	  {% if inline_admin_formset.opts.template == stacked_template %}
+        {% include stacked_template with indent=10 prev_prefix=recursive_formset.formset.prefix%}
+   	  {% else %}
+   	 	{% include tabular_template with indent=10  prev_prefix=recursive_formset.formset.prefix%}
+   	  {% endif %}
+    {% endfor %}
+  {% endif %}
 </div>{% endfor %}
 </div>
 
 <script type="text/javascript">
 (function($) {
-  $("#{{ inline_admin_formset.formset.prefix }}-group .inline-related").stackedFormset({
-    prefix: '{{ inline_admin_formset.formset.prefix }}',
+  $("#{{ recursive_formset.formset.prefix }}-group .inline-related").stackedFormset({
+    prefix: '{{ recursive_formset.formset.prefix }}',
     adminStaticPrefix: '{% static "admin/" %}',
-    deleteText: "{% trans "Remove" %}",
-    addText: "{% blocktrans with verbose_name=inline_admin_formset.opts.verbose_name|title %}Add another {{ verbose_name }}{% endblocktrans %}"
+    addText: "{% blocktrans with verbose_name=recursive_formset.opts.verbose_name|title %}Add another {{ verbose_name }}{% endblocktrans %}",
+    deleteText: "{% trans "Remove" %}"
   });
 })(django.jQuery);
 </script>
+{% endwith %}

-------- django/contrib/admin/templates/admin/edit_inline/tabular.html --------
index f2757ed..b1cb7f6 100644
@@ -1,29 +1,30 @@
 {% load i18n admin_static admin_modify %}
-<div class="inline-group" id="{{ inline_admin_formset.formset.prefix }}-group">
+{% with recursive_formset=inline_admin_formset stacked_template='admin/edit_inline/stacked.html' tabular_template='admin/edit_inline/tabular.html'%}
+<div class="inline-group {{ prev_prefix|default:"Root" }}-nested-inline" id="{{ recursive_formset.formset.prefix }}-group" style="margin-left: {{ indent|default:0 }}px">
   <div class="tabular inline-related {% if forloop.last %}last-related{% endif %}">
-{{ inline_admin_formset.formset.management_form }}
+{{ recursive_formset.formset.management_form }}
 <fieldset class="module">
-   <h2>{{ inline_admin_formset.opts.verbose_name_plural|capfirst }}</h2>
-   {{ inline_admin_formset.formset.non_form_errors }}
+   <h2>{{ recursive_formset.opts.verbose_name_plural|capfirst }}</h2>
+   {{ recursive_formset.formset.non_form_errors }}
    <table>
      <thead><tr>
-     {% for field in inline_admin_formset.fields %}
+     {% for field in recursive_formset.fields %}
        {% if not field.widget.is_hidden %}
          <th{% if forloop.first %} colspan="2"{% endif %}{% if field.required %} class="required"{% endif %}>{{ field.label|capfirst }}
          {% if field.help_text %}&nbsp;<img src="{% static "admin/img/icon-unknown.gif" %}" class="help help-tooltip" width="10" height="10" alt="({{ field.help_text|striptags }})" title="{{ field.help_text|striptags }}" />{% endif %}
          </th>
        {% endif %}
      {% endfor %}
-     {% if inline_admin_formset.formset.can_delete %}<th>{% trans "Delete?" %}</th>{% endif %}
+     {% if recursive_formset.formset.can_delete %}<th>{% trans "Delete?" %}</th>{% endif %}
      </tr></thead>
 
      <tbody>
-     {% for inline_admin_form in inline_admin_formset %}
+     {% for inline_admin_form in recursive_formset %}
         {% if inline_admin_form.form.non_field_errors %}
         <tr><td colspan="{{ inline_admin_form|cell_count }}">{{ inline_admin_form.form.non_field_errors }}</td></tr>
         {% endif %}
-        <tr class="form-row {% cycle "row1" "row2" %} {% if inline_admin_form.original or inline_admin_form.show_url %}has_original{% endif %}{% if forloop.last %} empty-form{% endif %}"
-             id="{{ inline_admin_formset.formset.prefix }}-{% if not forloop.last %}{{ forloop.counter0 }}{% else %}empty{% endif %}">
+        <tr class="form-row {% cycle "row1" "row2" %} {% if inline_admin_form.original or inline_admin_form.show_url %}has_original{% endif %}{% if forloop.last %} empty-form{% endif %} {{ recursive_formset.formset.prefix }}-not-nested"
+             id="{{ recursive_formset.formset.prefix }}-{% if not forloop.last %}{{ forloop.counter0 }}{% else %}empty{% endif %}">
         <td class="original">
           {% if inline_admin_form.original or inline_admin_form.show_url %}<p>
           {% if inline_admin_form.original %} {{ inline_admin_form.original }}{% endif %}
@@ -55,10 +56,23 @@
             {% endfor %}
           {% endfor %}
         {% endfor %}
-        {% if inline_admin_formset.formset.can_delete %}
+        {% if recursive_formset.formset.can_delete %}
           <td class="delete">{% if inline_admin_form.original %}{{ inline_admin_form.deletion_field.field }}{% endif %}</td>
         {% endif %}
         </tr>
+        {% if inline_admin_form.form.nested_formsets %}
+   	 	  {% for inline_admin_formset in inline_admin_form.form.nested_formsets %}
+   	 	  <tr class="nested-inline-row">
+   	 	    <td colspan="100%" style="border-top:none">
+	   	 	  {% if inline_admin_formset.opts.template == stacked_template %}
+	   	 	    {% include stacked_template with indent=0 prev_prefix=recursive_formset.formset.prefix %}
+	   	 	  {% else %}
+	   	 		{% include tabular_template with indent=0 prev_prefix=recursive_formset.formset.prefix %}
+	   	 	  {% endif %}
+   	 		</td>
+   	 	  </tr>
+     	  {% endfor %}
+   		{% endif %}
      {% endfor %}
      </tbody>
    </table>
@@ -67,13 +81,13 @@
 </div>
 
 <script type="text/javascript">
-
 (function($) {
-  $("#{{ inline_admin_formset.formset.prefix }}-group .tabular.inline-related tbody tr").tabularFormset({
-    prefix: "{{ inline_admin_formset.formset.prefix }}",
+  $("#{{ recursive_formset.formset.prefix }}-group .tabular.inline-related tbody tr.{{ recursive_formset.formset.prefix }}-not-nested").tabularFormset({
+    prefix: "{{ recursive_formset.formset.prefix }}",
     adminStaticPrefix: '{% static "admin/" %}',
-    addText: "{% blocktrans with inline_admin_formset.opts.verbose_name|title as verbose_name %}Add another {{ verbose_name }}{% endblocktrans %}",
+    addText: "{% blocktrans with recursive_formset.opts.verbose_name|title as verbose_name %}Add another {{ verbose_name }}{% endblocktrans %}",
     deleteText: "{% trans 'Remove' %}"
   });
 })(django.jQuery);
 </script>
+{% endwith %}

------------------------ django/contrib/admin/tests.py ------------------------
index 7c62c1a..6fe6216 100644
@@ -2,6 +2,7 @@ from django.test import LiveServerTestCase
 from django.utils.importlib import import_module
 from django.utils.unittest import SkipTest
 from django.utils.translation import ugettext as _
+from selenium import webdriver
 
 class AdminSeleniumWebDriverTestCase(LiveServerTestCase):
     webdriver_class = 'selenium.webdriver.firefox.webdriver.WebDriver'
@@ -13,6 +14,7 @@ class AdminSeleniumWebDriverTestCase(LiveServerTestCase):
             module, attr = cls.webdriver_class.rsplit('.', 1)
             mod = import_module(module)
             WebDriver = getattr(mod, attr)
+            #Avoid startup screen
             cls.selenium = WebDriver()
         except Exception as e:
             raise SkipTest('Selenium webdriver "%s" not installed or not '

----------------- tests/regressiontests/admin_inlines/admin.py -----------------
index cf51fa4..3f2d067 100644
@@ -123,6 +123,34 @@ class ChildModel1Inline(admin.TabularInline):
 
 class ChildModel2Inline(admin.StackedInline):
     model = ChildModel2
+    
+class FurnitureInline(admin.StackedInline):
+    model = Furniture
+    extra = 1
+    
+class InhabitantInline(admin.StackedInline):
+    model = Inhabitant
+    extra = 1
+    inlines = [ FurnitureInline, ]
+    
+class AppartementInline(admin.TabularInline):
+    model = Appartement
+    extra = 1
+    inlines = [ InhabitantInline, ]
+    
+class MonumentInline(admin.StackedInline):
+    model = Monument
+    extra = 1
+    
+class BuildingInline(admin.TabularInline):
+    model = Building
+    extra = 1
+    inlines = [ AppartementInline, ]
+    
+class CityInline(admin.StackedInline):
+    model = City
+    extra = 1
+    inlines = [BuildingInline, MonumentInline, ]
 
 
 site.register(TitleCollection, inlines=[TitleInline])
@@ -141,4 +169,11 @@ site.register(Holder4, Holder4Admin)
 site.register(Author, AuthorAdmin)
 site.register(CapoFamiglia, inlines=[ConsigliereInline, SottoCapoInline])
 site.register(ProfileCollection, inlines=[ProfileInline])
-site.register(ParentModelWithCustomPk, inlines=[ChildModel1Inline, ChildModel2Inline])
\ No newline at end of file
+site.register(ParentModelWithCustomPk, inlines=[ChildModel1Inline, ChildModel2Inline])
+site.register(Country, inlines=[CityInline])
+site.register(City)
+site.register(Building)
+site.register(Monument)
+site.register(Appartement)
+site.register(Inhabitant)
+site.register(Furniture)
\ No newline at end of file

---------------- tests/regressiontests/admin_inlines/models.py ----------------
index b004d5f..c51af58 100644
@@ -180,3 +180,51 @@ class Profile(models.Model):
     collection = models.ForeignKey(ProfileCollection, blank=True, null=True)
     first_name = models.CharField(max_length=100)
     last_name = models.CharField(max_length=100)
+    
+class Country(models.Model):
+    name = models.CharField(max_length=100)
+    
+    def __unicode__(self):
+        return self.name
+
+class City(models.Model):
+    name = models.CharField(max_length=100)
+    country = models.ForeignKey(Country)
+    
+    def __unicode__(self):
+        return self.name
+
+class Building(models.Model):
+    name = models.CharField(max_length=100)
+    city = models.ForeignKey(City)
+    
+    def __unicode__(self):
+        return self.name
+
+class Appartement(models.Model):
+    name = models.CharField(max_length=100)
+    building = models.ForeignKey(Building)
+    
+    def __unicode__(self):
+        return self.name
+
+class Inhabitant(models.Model):
+    name = models.CharField(max_length=100)
+    appartement = models.ForeignKey(Appartement)
+    
+    def __unicode__(self):
+        return self.name
+
+class Furniture(models.Model):
+    name = models.CharField(max_length=100)
+    inhabitant = models.ForeignKey(Inhabitant)
+    
+    def __unicode__(self):
+        return self.name
+    
+class Monument(models.Model):
+    name = models.CharField(max_length=100)
+    city = models.ForeignKey(City)
+    
+    def __unicode__(self):
+        return self.name
\ No newline at end of file

----------------- tests/regressiontests/admin_inlines/tests.py -----------------
index 5bb6077..a6ef27a0 100644
@@ -584,6 +584,59 @@ class SeleniumFirefoxTests(AdminSeleniumWebDriverTestCase):
             "%s.row1" % row_selector)), 2, msg="Expect two row1 styled rows")
         self.assertEqual(len(self.selenium.find_elements_by_css_selector(
             "%s.row2" % row_selector)), 1, msg="Expect one row2 styled row")
+        
+    def test_nested_add_links(self):
+        self.admin_login(username='super', password='secret')
+        self.selenium.get('%s%s' % (self.live_server_url,
+            '/admin/admin_inlines/country/add/')) 
+        self.assertEqual(len(self.selenium.find_elements_by_css_selector(
+            'tr.add-row')), 2)       
+        
+    def test_nested_adding_deleting(self):
+        self.admin_login(username='super', password='secret')
+        self.selenium.get('%s%s' % (self.live_server_url,
+            '/admin/admin_inlines/country/add/'))
+        
+        # Add some forms
+        self.selenium.find_element_by_link_text('Add another City').click()
+        self.selenium.find_element_by_link_text('Add another City').click()
+        # Add monument in first city
+        self.selenium.find_element_by_xpath('/html/body/div/div[3]/div/form/div[2]/div/div/div[2]/div[3]/a').click()
+        # Add building in second city
+        self.selenium.find_element_by_xpath('/html/body/div/div[3]/div/form/div[2]/div/div[2]/div/div/fieldset/table/tbody/tr[4]/td/a').click()
+        # Add apartement in second building of second city
+        self.selenium.find_element_by_xpath('/html/body/div/div[3]/div/form/div[2]/div/div[2]/div/div/fieldset/table/tbody/tr[4]/td/div/div/fieldset/table/tbody/tr[4]/td/a').click()
+        # Add inhabitants in third city
+        self.selenium.find_element_by_xpath('/html/body/div/div[3]/div/form/div[2]/div/div[3]/div/div/fieldset/table/tbody/tr[2]/td/div/div/fieldset/table/tbody/tr[2]/td/div/div[3]/a').click()
+        self.selenium.find_element_by_xpath('/html/body/div/div[3]/div/form/div[2]/div/div[3]/div/div/fieldset/table/tbody/tr[2]/td/div/div/fieldset/table/tbody/tr[2]/td/div/div[4]/a').click()
+        # Add furniture in first city
+        self.selenium.find_element_by_xpath('/html/body/div/div[3]/div/form/div[2]/div/div/div/div/fieldset/table/tbody/tr[2]/td/div/div/fieldset/table/tbody/tr[2]/td/div/div/div/div[3]/a').click()
+        # Check if everything went ok
+        pass
+        # Delete some stuff
+        pass
+        # Chek if everythin was deleted
+        pass
+    
+    def test_nested_inlines(self):
+        self.admin_login(username='super', password='secret')
+        self.selenium.get('%s%s' % (self.live_server_url,
+            '/admin/admin_inlines/country/add/'))
+        
+        # Enter some data
+        self.selenium.find_element_by_css_selector('#id_name').send_keys('Belgium')
+        self.selenium.find_element_by_css_selector('#id_city_set-0-name').send_keys('1')
+        self.selenium.find_element_by_css_selector('#id_city_set-0-building_set-0-name').send_keys('1.1')
+        self.selenium.find_element_by_css_selector('#id_city_set-0-building_set-0-appartement_set-0-name').send_keys('1.1.1')
+        self.selenium.find_element_by_css_selector('#id_city_set-0-building_set-0-appartement_set-0-inhabitant_set-0-name').send_keys('1.1.1.1')
+        self.selenium.find_element_by_css_selector('#id_city_set-0-building_set-0-appartement_set-0-inhabitant_set-0-furniture_set-0-name').send_keys('1.1.1.1.1')
+        self.selenium.find_element_by_css_selector('#id_city_set-0-monument_set-0-name').send_keys('Monument')
+        
+        # Save
+        self.selenium.find_element_by_xpath('/html/body/div/div[3]/div/form/div[2]/div[2]/input').click()
+        
+        
+        self.fail("ok")
 
 
 class SeleniumChromeTests(SeleniumFirefoxTests):