Ticket #8387: get_form+get_fieldsets-docs-02.2.diff

File get_form+get_fieldsets-docs-02.2.diff, 2.6 KB (added by jarrow, 8 years ago)
  • docs/ref/contrib/admin.txt

    587587                instance.save()
    588588            formset.save_m2m()
     590``get_form(self, request, obj=None, **kwargs)``
     593The ``get_form`` method is given the ``HttpRequest`` and a model
     594instance, but only if the user is changing the object. It can also be passed
     595keyword arguments to be used as attributes for the ``ModelForm.Meta``
     596class. The return value is a ``ModelForm``.
     598For example to dynamically add another field to the form when the user has extra rights::
     600    class MyModelAdminForm(forms.ModelForm):
     601        class Meta:
     602            model = MyModel
     603        extra_option = forms.BooleanField()
     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)
     611``get_fieldsets(self, request, obj=None)``
     614The ``get_fieldsets`` method is given the ``HttpRequest`` and a model
     615instance, but only if the user is changing the object. It returns the fieldsets
     616in the same format they are specified in the ``fieldsets`` attribute.
     618For example to display a smaller set of fields when the user is changing
     619rather than adding::
     621    from django.contrib.admin.util import flatten_fieldsets
     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')})]
     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)
     636.. admonition:: Note
     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``.
    590643``ModelAdmin`` media definitions
Back to Top