| 590 | ``get_form(self, request, obj=None, **kwargs)`` |
| 591 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 592 | |
| 593 | The ``get_form`` method is given the ``HttpRequest`` and a model |
| 594 | instance, but only if the user is changing the object. It can also be passed |
| 595 | keyword arguments to be used as attributes for the ``ModelForm.Meta`` |
| 596 | class. The return value is a ``ModelForm``. |
| 597 | |
| 598 | For example to dynamically add another field to the form when the user has extra rights:: |
| 599 | |
| 600 | class MyModelAdminForm(forms.ModelForm): |
| 601 | class Meta: |
| 602 | model = MyModel |
| 603 | extra_option = forms.BooleanField() |
| 604 | |
| 605 | class MyModelAdmin(admin.ModelAdmin): |
| 606 | def get_form(self, request, obj=None, **kwargs): |
| 607 | if request.user.has_perm("myapp.can_use_extra_option"): |
| 608 | return MyModelAdminForm |
| 609 | return super(MyModelAdmin, self).get_form(request, obj, **kwargs) |
| 610 | |
| 611 | ``get_fieldsets(self, request, obj=None)`` |
| 612 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 613 | |
| 614 | The ``get_fieldsets`` method is given the ``HttpRequest`` and a model |
| 615 | instance, but only if the user is changing the object. It returns the fieldsets |
| 616 | in the same format they are specified in the ``fieldsets`` attribute. |
| 617 | |
| 618 | For example to display a smaller set of fields when the user is changing |
| 619 | rather than adding:: |
| 620 | |
| 621 | from django.contrib.admin.util import flatten_fieldsets |
| 622 | |
| 623 | class MyModelAdmin(admin.ModelAdmin): |
| 624 | def get_fieldsets(self, request, obj=None): |
| 625 | if obj: |
| 626 | return [(None, {'fields': ('field_c', 'field_b')})] |
| 627 | return [(None, {'fields': ('field_a', 'field_b', 'field_c')})] |
| 628 | |
| 629 | def get_form(self, request, obj=None, **kwargs): |
| 630 | defaults = { |
| 631 | 'fields': flatten_fieldsets(self.get_fieldsets(request, obj)), |
| 632 | } |
| 633 | defaults.update(kwargs) |
| 634 | return super(MyModelAdmin, self).get_form(request, obj, **defaults) |
| 635 | |
| 636 | .. admonition:: Note |
| 637 | |
| 638 | If you return only a subset of your models fields in ``get_fieldsets`` you need |
| 639 | to override ``get_form`` as well and set the ``fields`` or ``exclude`` attribute. |
| 640 | Otherwise the form will expect *all* fields to be present and will either raise |
| 641 | validation errors on the missing fields or clear them if they have ``blank=True``. |
| 642 | |