============= Example Usage ============= Limiting widget queryset ------------------------ Consider a simple, naive example. We want to assign guests to hotel rooms, but for some certain reason we want to have a possibility to assign guests to hotels without assigning them directly to any room. Because of that, ``Guest`` will have two foreign keys (and a bit of redundancy): .. literalinclude:: ../example/limit_queryset/models.py We want an admin form widget, which will narrow room choices only to those corresponding to currently selected hotel. Before we write the admin and admin form, let's start with widgets: .. literalinclude:: ../example/limit_queryset/widgets.py ``HotelSelect2`` is an instance of original ``django_select2.ModelSelect2Widget`` widget without any modifications. ``RoomSelect2`` is an instance of extended ``linked_select2.LinkedModelSelect2Widget`` widget, which gives access to other (not submitted by the user yet) field values in ``get_queryset`` method. The ``RoomSelect2.get_queryset`` method is passed a form, which will contain a ``hotel`` field. The widget class connects the form field names with corresponding HTML input elements in the frontend and every time an AJAX fetch is happening, the values from these elements are passed as query parameters along with the search query. Both widgets will be used in a form of guest admin. Here we define the admin: .. literalinclude:: ../example/limit_queryset/admin.py And here we define the admin form: .. literalinclude:: ../example/limit_queryset/forms.py The ``GuestAdminForm.clean`` method ensures that if room is set, the hotel field must be set aswell and it must be the same exact hotel as the one of selected room. We override default widgets in ``GuestAdminForm.Meta`` class and we pass an argument ``form`` to ``RoomSelect2`` constructor - this form contains a hotel field. All HTML input elements with ids corresponding to field names of this form (only ``hotel`` in this case) will be connected with the room widget. Using generic relations ----------------------- Because of that, ``Guest`` will have two foreign keys (and a bit of redundancy): .. literalinclude:: ../example/generic_relation/models.py .. literalinclude:: ../example/generic_relation/widgets.py .. literalinclude:: ../example/generic_relation/admin.py .. literalinclude:: ../example/generic_relation/forms.py