The Admin interface is django's killer application. It reads the metadata in your mode and provides you with a powerful and usable interface. website administrators can use it to immediately add content to the website. The Admin interface is django's killer application. It reads the metadata in your mode and provides you with a powerful and usable interface. website administrators can use it to immediately add content to the website.
To use admin, follow these steps:
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 admin requires these four packages.
Set 'Django. contrib. messages. context_PRocessors.messages is added to TEMPLATE_CONTEXT_PROCESSORS, and make sure that 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 the admin.
Create a ModelAdmin for admin. py in the 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)
Configure admin access in 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 access http: // 127.0.0.1: 8000/admin/after creating a superuser.
ModelAdmin object
Register decorator
Register (* models [, site = django. admin. sites. site])
1.7 add a new one. Model and ModelAdmin can be registered as follows:
From django. contrib import admin
From. models import Author
@ Admin. register (Author)
Class AuthorAdmin (admin. ModelAdmin ):
Pass
You can register multiple models at a time and use your own custom 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 does Admin work?
After 'Django. contrib. admin' is added to INSTALLED_APPS, django automatically searches for the admin. py module in each app and loads the import.
Class apps. AdminConfig
Added Django 1.7.
Admin default AppConfig class. autodiscover () is executed when django is started ().
Class apps. SimpleAdminConfig
Added Django 1.7.
Similar to AdminConfig, autodiscover () is not executed ().
Autodiscover ()
Import the admin. py module of each app.
Django 1.7 changes:
In previous versions, you need 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 custom AdminSite, you need to load the subclass of ModelAdmin into your own code and register all the classes in the custom AdminSite. In this case, you need to stop automatic discovery (). you can replace 'Django. contrib. admin. apps. simpleadminconfig' in INSTALLED_APPS with 'Django. contrib. admin '.
ModelAdmin options
Actions
Admin actions list
Actions_on_top
Actions_on_bottom
The location of the action.
Date_hierarchy
Set date_hierarchy to the DateField or DateTimeField of the Model to add a date level for this Model in admin.
Fields
Exclude
Determines the fields displayed in the form of the Model. Fields is included, and exclude is excluded.
From django. contrib import admin
Class AuthorAdmin (admin. ModelAdmin ):
Fields = ('name', 'title ')
Class AuthorAdmin (admin. ModelAdmin ):
Exclude = ('Birth _ date ',)
Some fields can be placed on the same line, and the following url and title fields are placed on the same line:
Class FlatPageAdmin (admin. ModelAdmin ):
Fields = ('URL', 'title'), 'Content ')
Fieldsets
Fieldsets is a list of binary tuples (name, field_options). you can partition fields:
From django. contrib import admin
Class FlatPageAdmin (admin. ModelAdmin ):
Fieldsets = (
(None ,{
'Fields': ('URL', 'title', 'content', 'sites ')
}),
('Advanced options ',{
'Classe': ('collapse ',),
'Fields': ('enable _ comments ', 'registration _ required', 'Template _ name ')
}),
)
Name is the block title, and field_options is a dictionary.
Field_options has the following keys:
Fields
Fields, which are displayed in fieldset.
{
'Fields': ('First _ name', 'Last _ name'), 'address', 'city', 'State '),
}
Classes
List of additional CSS classes provided to fieldset.
Description
Additional text that can be displayed at the top of fieldset.
Filter_horizontal
Filter_vertical
When the Model has a ManyToManyField field, use filter_horizontal. filter_vertical can be selected from the existing options. One is horizontal and the other is vertical.
Form
Used form.
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 priority. In the preceding example, age is excluded, but name is displayed on the page.
Formfield_overrides
You can overwrite the options of some fields on the Model form interface and add custom parts for some specific fields.
For example, you want to use the 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 change list page of the Model. if list_display is not set, the admin interface automatically displays the _ unicode _ () results of the Model.
There are four values in list_display:
A field of model
List_display = ('First _ name', 'Last _ name ')
A callable function with the model parameter
Def upper_case_name (obj ):
Return ("% 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" % (obj. first_name, obj. last_name). upper ()
Upper_case_name.short_description = 'name'
An attribute of a 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 is displayed __.
ManyToManyField is not supported
If it is BooleanField, on or off is displayed.
If the provided string is a Model or ModelAdmin method or a callable function, django will automatically output HTML-escape. if you do not want to escape it, you can set the allow_tags of the method to True. To avoid XSS cross-site attacks, you must use format_html to escape user 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 }',
Self. color_code,
Self. first_name,
Self. last_name)
Colored_name.allow_tags = True
Class PersonAdmin (admin. ModelAdmin ):
List_display = ('First _ name', 'Last _ name', 'Colored _ name ')
If the provided string is a Model or ModelAdmin method or a callable function, and returns True or False, you can set the boolean attribute of the method to True. The on or off icon is 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_ties (self ):
Return self. birthday. strftime ('% Y') [: 3] = '20140901'
Born_in_effecties.boolean = True
Class PersonAdmin (admin. ModelAdmin ):
List_display = ('name', 'Born _ in_ties ')
The _ str _ or _ unicode _ method of the Model can also be used.
List_display = ('_ str _', 'Some _ other_field ')
If the items in list_display are not the actual fields of the database, they cannot be sorted. Otherwise, you can sort this item by setting the admin_order_field attribute to point out this fact.
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,
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', 'Colored _ first_name ')
In this way, django will sort by first_name in the order of colored_first_name. Reverse sorting:
Colored_first_name.admin_order_field = '-first_name'
Items in list_display can also be features:
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 field is linked to the change page of mode.
Class PersonAdmin (admin. ModelAdmin ):
List_display = ('First _ name', 'Last _ name', 'birthday ')
List_display_links = ('First _ name', 'Last _ name ')
List_editable
The field can be changed on the change list page. The fields must also be in list_display.
List_filter
The fields can be used as filters to filter the model. It can be a related domain.
Class PersonAdmin (admin. UserAdmin ):
List_filter = ('Company _ name ',)
List_max_show_all
Number of models on the show all page. the default value is 200.
List_per_page
The number of models on each change list page. the default value is 100.
List_select_related
It is related to select_related.
Ordering
Sort.
Paginator
Pagination. The default value is django. core. paginator. Paginator.
Prepopulated_fields
Preset fields.
Radio_fields
Use radio-button instead of select-box (when ForeignKey or the choices option is available ).
Class PersonAdmin (admin. ModelAdmin ):
Radio_fields = {"group": admin. VERTICAL}
Raw_id_fields
The field id is displayed for ForeignKey or ManyToManyField.
Class ArticleAdmin (admin. ModelAdmin ):
Raw_id_fields = ("newspaper ",)
Readonly_fields
Only readable and uneditable fields are allowed. You can also use the following methods:
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 ('
'),
'{0 }',
(Line,) for line in instance. get_full_address ()),
) Or "I can't determine 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
Save_as
When it is set to true, the "Save and add another" button on the change page will be replaced by "Save.
Save_on_top
When it is set to true, the save button is also displayed at the top of the change page.
Search_fields
You can search for fields.
View_on_site
Whether to display the View on site link.
Template options
Specify the options used by the template when customizing admin templates.
Add_form_template
The template used by add_view.
Change_form_template
The template used by change_view.
Change_list_template
Template used by changelist_view.
Delete_confirmation_template
The template used by delete_view.
Delete_selected_confirmation_template
The template used by delete_selected action method.
ModelAdmin. object_history_template
The template and log used by history_view.
The above is the content of Djangoadminsite (1) ModelAdminOptions. For more information, see PHP Chinese website (www.php1.cn )!