简体   繁体   中英

How to add new class created in models.py to admin.py (django)

Any suggestion on this please?

Initially I had class Customer(): in models.py

This is how the code in admin.py looked

from django.contrib import admin
from booknowapp.models import Customer

# Register your models here.
admin.site.register(Customer)

Now that I have added two new classes to models how do I register in admin for other new two classes to appear in the app? I am not sure of the syntax to be used.

If your added two new classes of models are ModelClass1 and ModelClass2 then you can register multiple models in admin.py like :

from django.contrib import admin
from booknowapp.models import Customer, ModelClass1, ModelClass2

myModels = [Customer, ModelClass1, ModelClass2]  # iterable list
admin.site.register(myModels)

OR

You can repeat admin.site.register for other two new classes just like your Customer .

If you extend the syntax that you have already used, it would simply be:

from django.contrib import admin
# wrap the line if it's too long
from booknowapp.models import (
    Customer,
    SecondModel,
    ThirdModel
)

# Register your models here.
admin.site.register(Customer)
admin.site.register(SecondModel)
admin.site.register(ThirdModel)

However, this will only give you the default admin model list views - which you will probably want to extend.

class CustomerAdmin(admin.ModelAdmin):
    """Specialised admin view for the Customer model."""
    # set the fields to display 
    list_display = ('name', 'address', 'registered')

# register your Customer model, using the CustomerAdmin view
admin.site.register(Customer, CustomerAdmin)

The ModelAdmin has lots more functionality that you can leverage - search fields, filtering, custom fields, custom actions ('Activate customer'), which you can read about here - http://www.djangobook.com/en/2.0/chapter06.html#custom-modeladmin-classes

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM