views:

17

answers:

2

I was wondering how they made it possible to display more fields in the User page of the djagno admin site. If you create a new User you only have some basic fields to fill in but if you reopen that user (edit mode) then you see a lot more fields to fill in.

Im trying to achieve the same, I had a look at the add_form.html template but I can't really get my head around it. I guess Im looking for a way of specifying different fields = [] sets based on the edit status of the document. mmh.

thanks!

+1  A: 

The answer lies in the custom admin class registered for the User model. It overrides a couple of methods on ModelAdmin and checks to see whether the current request is creating a new User (in which case the bare-bones form class for adding accounts is used) or editing an existing one (in which case a full form is shown).

James Bennett
In particular, see `get_form`: http://code.djangoproject.com/browser/django/trunk/django/contrib/auth/admin.py#L63
Dominic Rodger
umh.... thanks for the link. I can't really understand the code (or better how it works). Is obj set to None when editing the form? What does the defaults object do? I would be super grateful if you could lay down a quick example on how I could use this functionality for a model of my own (displaying some fields in creation mode and some others in editing mode). THANKS !
mαττjαĸøb
A: 

Here's my try. When I try to create a new item (Add) it shows only certain fields but then when I hit save it returns an error:

DoesNotExist

in /Library/Python/2.6/site-packages/django/db/models/fields/related.py in get, line 288

admin.py

    from django.contrib import admin
    from myapp.catalog.models import Model
    from myapp.catalog.forms import ProductAdminForm, ProductAddForm

    class ProductAdmin(admin.ModelAdmin):

        form = ProductAdminForm

        #...

        add_form = ProductAddForm

        def get_form(self, request, obj=None, **kwargs):
            defaults = {}
            if obj is None:
                defaults.update({
                    'form': self.add_form,
                })
            defaults.update(kwargs)
            return super(ProductAdmin, self).get_form(request, obj, **defaults)

forms.py

from myapp.catalog.models import Product

class ProductAdminForm(forms.ModelForm):

    class Meta:
        model = Product
        #...

class ProductAddForm(forms.ModelForm):
    class Meta:
      model = Product
      fields = ("model", "colour",)
mαττjαĸøb