Add another popup outside the admin

This documentation drives throught the example app non_admin_add_another which lives in test_project.

Implementing this feature is utterly simple and can be done in two steps:

  • make your create view to return some script if called with _popup=1,
  • add add_another_url_name attribute to your Autocomplete,

Warning

Note that this feature was added in version 1.0.21, if you have overloaded autocomplete_light/static.html from a previous version then you should make it load autocomplete_light/addanother.js to get this new feature.

Specifications

Consider such a model:

from __future__ import unicode_literals

from django.core import urlresolvers
from django.db import models
from django.utils.encoding import python_2_unicode_compatible


@python_2_unicode_compatible
class NonAdminAddAnotherModel(models.Model):
    name = models.CharField(max_length=100)
    widgets = models.ManyToManyField('self', blank=True)

    def get_absolute_url(self):
        return urlresolvers.reverse(
            'non_admin_add_another_model_update', args=(self.pk,))

    def __str__(self):
        return self.name

And we want to have add/update views outside the admin, with autocompletes for relations as well as a +/add-another button just like in the admin.

Technical details come from a blog post written by me a couple years ago, Howto: javascript popup form returning value for select like Django admin for foreign keys.

Create view

A create view opened via the add-another button should return such a body:

<script type="text/javascript">
opener.dismissAddAnotherPopup(
    window,
    "name of created model",
    "id of created model"
);
</script>

Note that you could also use autocomplete_light.CreateView which simply wraps around django.views.generic.edit.CreateView.form_valid() to do that, example usage:

import autocomplete_light.shortcuts as al

from autocomplete_light.compat import url, urls
from django.views import generic

from .forms import NonAdminAddAnotherModelForm
from .models import NonAdminAddAnotherModel

urlpatterns = urls([
    url(r'$', al.CreateView.as_view(
        model=NonAdminAddAnotherModel, form_class=NonAdminAddAnotherModelForm),
        name='non_admin_add_another_model_create'),
    url(r'(?P<pk>\d+)/$', generic.UpdateView.as_view(
        model=NonAdminAddAnotherModel, form_class=NonAdminAddAnotherModelForm),
        name='non_admin_add_another_model_update'),
])

Note

It is not mandatory to use url namespaces.

Autocompletes

Simply register an Autocomplete for widget, with an add_another_url_name argument, for example:

import autocomplete_light.shortcuts as autocomplete_light

from .models import NonAdminAddAnotherModel

autocomplete_light.register(NonAdminAddAnotherModel,
    add_another_url_name='non_admin_add_another_model_create')