Django admin site: how does the "Add User" page work (more fields when editing)?

I was wondering how they displayed more fields on the User page of the Django admin site. If you create a new user, you only have the basic fields to fill in, but if you open the user again (edit mode), you will see many more fields to fill out.

I try to achieve the same, I looked at the template add_form.html, but I can’t deceive him. I assume that I am looking for a way to set different fields = [] based on the editing status of the document.

Thank!

+1
source share
2 answers

, User. ModelAdmin , User ( ) ( ).

+2

. (Add), , , "", :

DoesNotExist

/Library/Python/2.6/site-packages/django/db/models/fields/related.py , 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",)
+1

Source: https://habr.com/ru/post/1791104/


All Articles