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