Home > Backend Development > Python Tutorial > Djangoadminsite(一)ModelAdminOptions

Djangoadminsite(一)ModelAdminOptions

黄舟
Release: 2016-12-23 17:44:11
Original
1329 people have browsed it

Admin management interface is Django’s killer application. It reads the metadata in your schema and then provides you with a powerful and usable interface that website administrators can use to instantly add content to the website.

To use admin, you can follow the steps below:

Add 'django.contrib.admin' to the INSTALLED_APPS configuration of setting.

Ensure that INSTALLED_APPS contains 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.messages' and 'django.contrib.sessions.', Django's admin needs these 4 packages.

Add 'django.contrib.messages.context_PRocessors.messages' to TEMPLATE_CONTEXT_PROCESSORS and make sure MIDDLEWARE_CLASSES contains 'django.contrib.auth.middleware.AuthenticationMiddleware' and 'django.contrib.messages.middleware.MessageMiddleware'. (Added by default)

Determine which Models need to be applied to admin.

Create a ModelAdmin in admin.py in each app that requires admin.

Register Model and ModelAdmin

from django.contrib import admin
from myproject.myapp.models import Author

class AuthorAdmin(admin.ModelAdmin):
pass
admin.site.register(Author, AuthorAdmin)

will The admin access configuration is in the URLconf

from django.contrib import admin
admin.autodiscover()

# And include this URLpattern...
urlpatterns = patterns('',
# ...
(r'^admin/ ', include(admin.site.urls)),
# ...
)

Run python manage.py migrate to remind you to create superuser and you can access http://127.0.0.1:8000/admin/.

ModelAdmin object

register decorator

register(*models[, site=django.admin.sites.site])

Newly added in 1.7. Model and ModelAdmin can be registered like this:

from django.contrib import admin
from .models import Author

@admin.register(Author)
class AuthorAdmin(admin.ModelAdmin):
pass

You can register multiple Models at one time , and you can use your own customized AdminSite:

from django.contrib import admin
from .models import Author, Reader, Editor
from myproject.admin_site import custom_admin_site

@admin.register(Author, Reader, Editor, site=custom_admin_site )
class PersonAdmin(admin.ModelAdmin):
Pass

How Admin works

When 'django.contrib.admin' is added to INSTALLED_APPS, django will automatically find the admin.py module in each app and import loading.

class apps.AdminConfig
Django 1.7 new.
admin default AppConfig class. Autodiscover() will be executed when Django starts.

class apps.SimpleAdminConfig
New in Django 1.7.
Similar to AdminConfig, autodiscover() will not be executed.

autodiscover()
import the admin.py module of each app.

Django 1.7 changes:
In previous versions, you needed to manually start this method in urls.py to find the admin.py of each app. After 1.7, AdminConfig will automatically execute this method.

If you are using a customized AdminSite, you need to load the subclasses of ModelAdmin into your own code and register them all in the customized AdminSite. In this case, you need to stop automatic discovery(), and you can replace 'django.contrib.admin' in INSTALLED_APPS with 'django.contrib.admin.apps.SimpleAdminConfig'.

ModelAdmin options

actions

List of admin actions

actions_on_top
actions_on_bottom

action location.

date_hierarchy

Set date_hierarchy to the Model's DateField or DateTimeField to add a date hierarchy to this Model in admin.

fields

exclude

determines which fields are displayed in the Model's form. fields include, exclude excludes.

from django.contrib import admin

class AuthorAdmin(admin.ModelAdmin):
fields = ('name', 'title')

class AuthorAdmin(admin.ModelAdmin):
exclude = ('birth_date',)

You can put some fields on the same line, such as the following url and title fields on the same line:

class FlatPageAdmin(admin.ModelAdmin):
fields = (('url', 'title'), 'content')

fieldsets

fieldsets is a list of double tuples (name, field_options), and fields can be divided into chunks:

from django.contrib import admin

class FlatPageAdmin(admin.ModelAdmin):
fieldsets = (
      (None ) , {  ' fields': ('enable_comments', 'registration_required', 'template_name')
  }),
  )

name is the title of the block and field_options is a dictionary.

field_options keys have the following types:

fields

tuples of field names, displayed in fieldset

{
'fields': (('first_name', 'last_name'), 'address', 'city ', 'state'),
}

classes

A list of additional CSS classes provided to the fieldset.

Description

Extra text that can be displayed at the top of the fieldset.

filter_horizontal
filter_vertical

When the Model has a ManyToManyField field, use filter_horizontal and filter_vertical to select multiple options from the existing options. One is horizontal and one is vertical.

form

The form used.

from django import forms
from django.contrib import admin
from myapp.models import Person

class PersonForm(forms.ModelForm):

class Meta:
model = Person
exclude = ['name']

class PersonAdmin(admin.ModelAdmin):
exclude = ['age']
form = PersonForm

When a conflict occurs, ModelAdmin takes precedence. In the above example, age will be excluded, but name will be displayed on the page.

formfield_overrides

You can override the options of some fields in the Model form interface and add your own customized widgets for some specific types of fields

For example, if you want to use a rich text editor for the TextField field of your Model:

from django.db import models
from django.contrib import admin

# Import our custom widget and our model from where they're defined
from myapp.widgets import RichTextEditorWidget
from myapp.models import MyModel

class MyModelAdmin(admin.ModelAdmin):
formfield_overrides = {
            models.TextField: {'widget': RichTextEditorWidget},
  }

list_display

Fields that can be displayed on the Model's change list page. If list_display is not set, the admin interface will automatically display the Model's __unicode__() result.

There are 4 values ​​in list_display:

A field of model

list_display = ('first_name', 'last_name')

A callable function that takes model as a parameter

def upper_case_name(obj):
return ("%s %s" % (obj.first_name, obj.last_name)).upper()
upper_case_name.short_description = 'Name'

class PersonAdmin(admin.ModelAdmin):
list_display = (upper_case_name,) 

An attribute of ModelAdmin, similar to a callable function

class PersonAdmin(admin.ModelAdmin):
list_display = ('upper_case_name',)

def upper_case_name(self, obj):
return ("%s %s" % (obj.first_name, obj.last_name)).upper()
upper_case_name.short_description = 'Name'

An attribute of Model, similar to a callable function

from django.db import models
from django.contrib import admin

class Person(models.Model):
name = models.CharField(max_length=50)
birthday = models.DateField()

def decade_born_in(self):
return self.birthday.strftime('%Y') [:3] + "0's"
 decade_born_in.short_description = 'Birth decade'

class PersonAdmin(admin.ModelAdmin):
list_display = ('name', 'decade_born_in')

Note:

If the field is ForeignKey , the __unicode__ of the foreign key will be displayed.

ManyToManyField is not supported

If it is a BooleanField, it will display on or off.

If the provided string is a Model or ModelAdmin method or a callable function, Django will automatically HTML-escape the output. If you don’t want to escape, you can set the method’s allow_tags to True. In order to avoid XSS cross-site attacks, you need to use format_html to escape the user's input:

from django.db import models
from django.contrib import admin
from django.utils.html import format_html

class Person(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField (max_length=50)
color_code = models.CharField(max_length=6)

def colored_name(self):
return format_html('{1} {2 )

colored_name.allow_tags = True

class PersonAdmin(admin.ModelAdmin):
list_display = ('first_name', 'last_name ', 'colored_name') 


If the provided string is a method of Model or ModelAdmin or a callable function and returns True or False, the boolean attribute of the method can be set to True. In this way, the on or off icon will be displayed on the page.

from django.db import models

from django.contrib import admin

class Person(models.Model):
first_name = models.CharField(max_length=50)
birthday = models.DateField()

def born_in_fifties(self ):
        return self.birthday.strftime('%Y')[:3] == '195'
  born_in_fifties.boolean = True

class PersonAdmin(admin.ModelAdmin):
  list_display = ('name', 'born_in_fifties ') 


Model's __str__ or __unicode__ method can also be used

list_display = ('__str__', 'some_other_field')

If the items in list_display are not actual fields of the database, then this cannot be used Item sorting. Otherwise, you can order by this item, and you can point out this fact by setting the admin_order_field attribute.

from django.db import models

from django.contrib import admin

from django.utils.html import format_html


class Person(models.Model):
first_name = models.CharField(max_length=50)
color_code = models. CharField(max_length=6)

def colored_first_name(self):
return format_html('{1}',
self.color_code, R Self.first_name)

Colored_first_name.allow_tags = True
COLORED_FIRST_NAME.ADMIN_ORDER_FIELD = 'FIRST_NAME'CLASS Personadmin (Admin.modeLadmin ): _ List_display = ('first_name', 'colord_first_name')


This is trying to sort with colord_first_name , django will sort by first_name. Can be sorted in reverse:

colored_first_name.admin_order_field = '-first_name'


items in list_display can also be attributes:

class Person(object):

first_name = models.CharField(max_length=50)

last_name = models .CharField(max_length=50)

def my_property(self):

return self.first_name + ' ' + self.last_name

my_property.short_description = "Full name of the person"


full_name = property(my_property)

class PersonAdmin(admin.ModelAdmin):
list_display = ('full_name',) 


list_display_link

The fields will be linked to the mode change page

class PersonAdmin(admin.ModelAdmin):
list_display = ('first_name' , 'last_name', 'birthday')

list_display_links = ('first_name', 'last_name')

list_editable

The fields can be changed on the change list page. The fields in it must also be in list_display.

list_filter

The fields in it can be used as filters to filter the model. Can be a related domain.

class PersonAdmin(admin.UserAdmin):

list_filter = ('company__name',)

list_max_show_all

show the number of models on all pages, default 200.


list_per_page

The number of models in each change list page, the default is 100.

list_select_related

is related to select_related().

ordering

sorting. Pagination used by

paginator

. Default django.core.paginator.Paginator.

prepopulated_fields

Prepopulated fields.

radio_fields

Use radio-button instead of select-box (ForeignKey or when there is choices option).

class PersonAdmin(admin.ModelAdmin):
radio_fields = {"group": admin.VERTICAL}

raw_id_fields

will display the id of the field, used for ForeignKey or ManyToManyField.

class ArticleAdmin(admin.ModelAdmin):
raw_id_fields = ("newspaper",)

readonly_fields

Only readable and non-editable fields. It can also be the method:

from django.contrib import admin
from django.utils.html import format_html_join
from django.utils.safestring import mark_safe

class PersonAdmin(admin.ModelAdmin):
readonly_fields = ('address_report',)

def address_report(self, instance):
# assuming get_full_address() returns a list of strings
# for each line of the address and you want to separate each
# line by a linebreak
return format_html_join(
Mark_safe('< ;br/>'),
                                                                                                                                                                 this address."

# short_description functions like a model field's verbose_name
address_report.short_description = "Address"
# in this example, we have used HTML tags in the output
address_report.allow_tags = True


When save_as

is set to True, the "Save and add another" button on the change page will be replaced by "Save as".

save_on_top

When set to True, there will also be a save button at the top of the change page.

search_fields

Searchable fields.

view_on_site

Whether to display the View on site link.

template options

Some options used to specify the template when customizing the admin template.

add_form_template

add_view() The template used.


change_form_template

change_view() The template used.


change_list_template

changelist_view() The template used.


delete_confirmation_template

delete_view().


delete_selected_confirmation_template

template used by delete_selected action method.


ModelAdmin.object_history_template

history_view() template, log.


The above is the content of Djangoadminsite (1) ModelAdminOptions. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template