Django admin site: How does the Add User page work (more fields on edit)?

南笙酒味 提交于 2020-01-13 07:00:28

问题


I was wondering how they made it possible to display more fields in the User page of the Django 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.

I'm 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 I'm looking for a way of specifying different fields = [] sets based on the edit status of the document.

Thanks!


回答1:


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).




回答2:


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",)


来源:https://stackoverflow.com/questions/3929149/django-admin-site-how-does-the-add-user-page-work-more-fields-on-edit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!