# Path: popupcrud/widgets.py
# class RelatedFieldPopupFormWidget(RelatedFieldWidgetWrapper):
#     """
#     A modified version of django.admin's `RelatedFieldWidgetWrapper`,
#     adds a **Create New** hyperlink to the bottom of the select box of a related
#     object field. This hyperlink will have CSS class `add-another` and its id
#     set to `add_id_<field_name>` with its href set to `javascript:void(0);`.
# 
#     The associated JavaScript `popupcrud/js/popupcrud.js`, binds a click handler
#     to `.add-another`, which then activates the Bootstrap modal associated with
#     the hyperlink. The modal body will be filled with the HTML response from
#     an AJAX request to the hyperlink's `data-url` attribute value.
# 
#     The JavaScript file is added to the form's media list automatically.
# 
#     """
#     def __init__(self, widget, new_url, *args, **kwargs):
#         """
#         Constructor takes the following required parameters:
# 
#         :param widget: The underlying `Select` widget that this widget replaces.
#         :param url: The url to load the HTML content to fill the assocaited modal
#             body.
#         """
#         _unused = args, kwargs
#         self.widget = widget
#         self.new_url = str(new_url)
#         self.choices = widget.choices
#         self.needs_multipart_form = getattr(widget, "needs_multipart_form", False)
#         self.attrs = getattr(widget, 'attrs', None)
# 
#     def render(self, name, value, *args, **kwargs):
#         widget = self.widget
#         widget.choices = self.choices
#         output = [self.widget.render(name, value, *args, **kwargs)]
#         output.append(u'<a href="javascript:void(0);" class="add-another" id="add_id_{0}" data-url="{1}">'\
#                       .format(name, self.new_url))
#         output.append(u'<small>%s</small></a>' % ugettext('New {0}').\
#                       format(camel_case_to_spaces(name).title()))
#         return mark_safe(u''.join(output))
# 
#     class Media:
#         js = ('popupcrud/js/popupcrud.js',)


from collections import OrderedDict
from django import forms
from django.db import transaction
from django.conf import settings
from django.conf.urls import include, url
from django.core.exceptions import (
    FieldDoesNotExist, ObjectDoesNotExist)
from django.shortcuts import render
from django.views import generic
from django.http import JsonResponse
from django.template import loader
from django.contrib.auth.mixins import PermissionRequiredMixin
from django.contrib import messages
from django.utils.decorators import classonlymethod
from django.utils.translation import ugettext_lazy as _, ugettext, override
from django.utils.http import urlencode
from django.utils.safestring import mark_safe
from django.utils.functional import cached_property
    from django.utils import six
from pure_pagination import PaginationMixin
from .widgets import RelatedFieldPopupFormWidget
import copy
    import six
        if 'formset' not in kwargs:
            formset = self._viewset.get_formset()
            if formset:
                kwargs['formset'] = formset
        return super(AjaxObjectFormMixin, self).get_context_data(**kwargs)

    def get_ajax_response(self):
        return JsonResponse({
            'name': str(self.object), # object representation
            'pk': self.object.pk          # object id
        })

    # following two methods are applicable only to Create/Edit views
    def get_form_class(self):
        if getattr(self._viewset, 'form_class', None):
            return self._viewset.form_class
        return super(AjaxObjectFormMixin, self).get_form_class()

    def get_form(self, form_class=None):
        form = super(AjaxObjectFormMixin, self).get_form(form_class)
        if not getattr(self._viewset, 'form_class', None):
            self._init_related_fields(form)
        return form

    def _init_related_fields(self, form):
        related_popups = getattr(self._viewset, 'related_object_popups', {})
        for fname in related_popups:
            if fname in form.fields:
                _ = form.fields[fname]
                if isinstance(form.fields[fname], forms.ModelChoiceField):

# Path: popupcrud/widgets.py
# class RelatedFieldPopupFormWidget(RelatedFieldWidgetWrapper):
#     """
#     A modified version of django.admin's `RelatedFieldWidgetWrapper`,
#     adds a **Create New** hyperlink to the bottom of the select box of a related
#     object field. This hyperlink will have CSS class `add-another` and its id
#     set to `add_id_<field_name>` with its href set to `javascript:void(0);`.
# 
#     The associated JavaScript `popupcrud/js/popupcrud.js`, binds a click handler
#     to `.add-another`, which then activates the Bootstrap modal associated with
#     the hyperlink. The modal body will be filled with the HTML response from
#     an AJAX request to the hyperlink's `data-url` attribute value.
# 
#     The JavaScript file is added to the form's media list automatically.
# 
#     """
#     def __init__(self, widget, new_url, *args, **kwargs):
#         """
#         Constructor takes the following required parameters:
# 
#         :param widget: The underlying `Select` widget that this widget replaces.
#         :param url: The url to load the HTML content to fill the assocaited modal
#             body.
#         """
#         _unused = args, kwargs
#         self.widget = widget
#         self.new_url = str(new_url)
#         self.choices = widget.choices
#         self.needs_multipart_form = getattr(widget, "needs_multipart_form", False)
#         self.attrs = getattr(widget, 'attrs', None)
# 
#     def render(self, name, value, *args, **kwargs):
#         widget = self.widget
#         widget.choices = self.choices
#         output = [self.widget.render(name, value, *args, **kwargs)]
#         output.append(u'<a href="javascript:void(0);" class="add-another" id="add_id_{0}" data-url="{1}">'\
#                       .format(name, self.new_url))
#         output.append(u'<small>%s</small></a>' % ugettext('New {0}').\
#                       format(camel_case_to_spaces(name).title()))
#         return mark_safe(u''.join(output))
# 
#     class Media:
#         js = ('popupcrud/js/popupcrud.js',)


# Path: popupcrud/views.py
from collections import OrderedDict
from django import forms
from django.db import transaction
from django.conf import settings
from django.conf.urls import include, url
from django.core.exceptions import (
    FieldDoesNotExist, ObjectDoesNotExist)
from django.shortcuts import render
from django.views import generic
from django.http import JsonResponse
from django.template import loader
from django.contrib.auth.mixins import PermissionRequiredMixin
from django.contrib import messages
from django.utils.decorators import classonlymethod
from django.utils.translation import ugettext_lazy as _, ugettext, override
from django.utils.http import urlencode
from django.utils.safestring import mark_safe
from django.utils.functional import cached_property
    from django.utils import six
from pure_pagination import PaginationMixin
from .widgets import RelatedFieldPopupFormWidget
import copy
    import six

        if 'formset' not in kwargs:
            formset = self._viewset.get_formset()
            if formset:
                kwargs['formset'] = formset
        return super(AjaxObjectFormMixin, self).get_context_data(**kwargs)

    def get_ajax_response(self):
        return JsonResponse({
            'name': str(self.object), # object representation
            'pk': self.object.pk          # object id
        })

    # following two methods are applicable only to Create/Edit views
    def get_form_class(self):
        if getattr(self._viewset, 'form_class', None):
            return self._viewset.form_class
        return super(AjaxObjectFormMixin, self).get_form_class()

    def get_form(self, form_class=None):
        form = super(AjaxObjectFormMixin, self).get_form(form_class)
        if not getattr(self._viewset, 'form_class', None):
            self._init_related_fields(form)
        return form

    def _init_related_fields(self, form):
        related_popups = getattr(self._viewset, 'related_object_popups', {})
        for fname in related_popups:
            if fname in form.fields:
                _ = form.fields[fname]
                if isinstance(form.fields[fname], forms.ModelChoiceField):

                    form.fields[fname].widget = RelatedFieldPopupFormWidget(