Django-Admin,

Source: Internet
Author: User

Django-Admin,

Author: Wu peiqi

Source: http://www.cnblogs.com/wupeiqi/articles/7444717.html
The copyright of this article is shared by the author and the blog. You are welcome to repost this article, but you must keep this statement without the author's consent and provide a connection to the original article on the article page.

 

1. the built-in Admin of Django is a component provided for adding, deleting, modifying, and querying data tables in the model. The usage methods include:
1 dependent APP: 2 django. contrib. auth 3 django. contrib. contenttypes 4 django. contrib. messages 5 django. contrib. sessions 6 7 Template context_processors: 8 django. contrib. auth. context_processors.auth 9 django. contrib. messages. context_processors.messages10 11 middleware: 12 django. contrib. auth. middleware. authenticationMiddleware 13 django. contrib. messages. middleware. messageMiddleware
Django Admin internal dependency 2. Configure routes
1 urlpatterns = [2         url(r'^admin/', admin.site.urls),3     ]

You can create some route ing relationships for the current route:

/Admin/
/Admin/login/
/Admin/logout/
/Admin/password_change/
/Admin/password_change/done/

/Admin/app name/model name/
/Admin/app name/model name/add/
/Admin/app name/model name/ID value/history/
/Admin/app name/model name/ID value/change/
/Admin/app name/model name/ID value/delete/

3. Customize Admin

In admin. py, you only need to register a class in Mode to add the delete, modify, and query function in Admin. For example:

1 admin.site.register(models.UserInfo)

However, this method is relatively simple. To perform more custom operations, you need to use ModelAdmin, such:

Method 1: 2 class UserAdmin (admin. modelAdmin): 3 list_display = ('user', 'pwd',) 4 5 admin. site. register (models. userInfo, UserAdmin) # The first parameter can be list 6 7 8 Mode 2: 9 @ admin. register (models. userInfo) # The first parameter can be list 10 class UserAdmin (admin. modelAdmin): 11 list_display = ('user', 'pwd ',)

ModelAdmin provides a large number of customizable functions, such:

1. list_display: Custom columns displayed during the list.
1 @admin.register(models.UserInfo)2 class UserAdmin(admin.ModelAdmin):3     list_display = ('user', 'pwd', 'xxxxx')4  5     def xxxxx(self, obj):6         return "xxxxx"
2. list_display_links. You can click to jump to the Custom column during the list.
1 @admin.register(models.UserInfo)2 class UserAdmin(admin.ModelAdmin):3     list_display = ('user', 'pwd', 'xxxxx')4     list_display_links = ('pwd',)
3. list_filter: the quick filter on the right side of the List is customized.
1 from django. utils. translation import ugettext_lazy as _ 2 3 @ admin. register (models. userInfo) 4 class UserAdmin (admin. modelAdmin): 5 list_display = ('user', 'pwd') 6 7 class Ugg (admin. simpleListFilter): 8 title = _ ('Decade born') 9 parameter_name = 'xxxxxx' 10 11 def lookups (self, request, model_admin ): 12 "13 display filtering options 14: param request: 15: param model_admin: 16: return: 17" "18 return models. userGroup. objects. values_list ('id', 'title') 19 20 def queryset (self, request, queryset): 21 "" 22. When you click query, filter 23: param request: 24: param queryset: 25: return: 26 "" 27 v = self. value () 28 return queryset. filter (ug = v) 29 30 list_filter = ('user', Ugg ,)
4. list_select_related
1 # pagination, number of entries per page 2 list_per_page = 1003 4 # pagination, show all (real data <only when this value is set) 5 list_max_show_all = 2006 7 # page plug-in 8 paginator = Paginator
6. list_editable: columns that can be edited during the list.
1 @admin.register(models.UserInfo)2 class UserAdmin(admin.ModelAdmin):3     list_display = ('user', 'pwd','ug',)4     list_editable = ('ug',)
7. search_fields: Fuzzy search function in list
1 @admin.register(models.UserInfo)2 class UserAdmin(admin.ModelAdmin):3      4     search_fields = ('user', 'pwd')
8. date_hierarchy: searches for the Date and DateTime types in the list.
1 @admin.register(models.UserInfo)2 class UserAdmin(admin.ModelAdmin):3  4     date_hierarchy = 'ctime'
9. preserve_filters, detailed page, delete, modify, and whether to retain the original Search Condition 10 after the update jumps back to the list. save_as = False, detailed page, the button is "Sava as new" or "Sava and add another" 11. save_as_continue = True. Click Save and edit.
1 save_as_continue = True2 3 # If save_as = True and save_as_continue = True, click the "Sava as new" button to continue editing. 4 # If save_as = True and save_as_continue = False, click the "Sava as new" button and return to the list. 5 6 New in Django 1.10.
12. save_on_top = False. On the details page, whether to display the SAVE and delete buttons at the top of the page 13. inlines: Details page. If other tables and the current table are used as FK, the details page can be dynamically added or deleted.
1 class UserInfoInline(admin.StackedInline): # TabularInline2     extra = 03     model = models.UserInfo4  5  6 class GroupAdminMode(admin.ModelAdmin):7     list_display = ('id', 'title',)8     inlines = [UserInfoInline, ]
14. Custom Actions in action when listing
1 @ admin. register (models. userInfo) 2 class UserAdmin (admin. modelAdmin): 3 4 # specific method for customizing Action Behavior 5 def func (self, request, queryset): 6 print (self, request, queryset) 7 print (request. POST. getlist ('_ selected_action') 8 9 func. short_description = "Custom Actions for Chinese display" 10 actions = [func,] 11 12 # Action options are displayed at the top of the page 13 actions_on_top = True14 # Action options are displayed at the bottom of the page 15 actions_on_bottom = False16 17 # Whether to display the number of choices 18 actions_selection_counter = True
15. Customize HTML templates
1 add_form_template = None2 change_form_template = None3 change_list_template = None4 delete_confirmation_template = None5 delete_selected_confirmation_template = None6 object_history_template = None
16. raw_id_fields. The details page is displayed in the Input box for the FK and M2M fields.
1 @ admin. register (models. UserInfo) 2 class UserAdmin (admin. ModelAdmin): 3 4 raw_id_fields = ('fk field', 'm2m field ',)
17. fields: the field is displayed on the details page.
1 @admin.register(models.UserInfo)2 class UserAdmin(admin.ModelAdmin):3     fields = ('user',)
18. exclude: the excluded fields on the details page.
1 @admin.register(models.UserInfo)2 class UserAdmin(admin.ModelAdmin):3     exclude = ('user',)
19. readonly_fields: Read-Only field on the detailed page
1 @admin.register(models.UserInfo)2 class UserAdmin(admin.ModelAdmin):3     readonly_fields = ('user',)
20. fieldsets: Use the fieldsets label to split and display the data on the details page.
1 @ admin. register (models. userInfo) 2 class UserAdmin (admin. modelAdmin): 3 fieldsets = (4 ('basic data', {5 'fields': ('user', 'pwd', 'ctime',) 6 }), 7 ('others', {8' classs': ('collapse', 'wide ', 'extrapretty'), # 'collapse', 'wide ', 'extrapretty '9' fields': ('user', 'pwd'), 10}), 11)
21. When M2M is displayed on the details page, move the data (Direction: up/down and left/right)
1 @ admin. register (models. UserInfo) 2 class UserAdmin (admin. ModelAdmin): 3 filter_vertical = ("m2m field",) # Or filter_horizontal = ("m2m field ",)
22. ordering: data sorting rules in the list
1 @ admin. register (models. userInfo) 2 class UserAdmin (admin. modelAdmin): 3 ordering = ('-id',) 4 or 5 def get_ordering (self, request): 6 return ['-id',]
23. view_on_site: whether to display view on set on the page during editing
1 view_on_site = False2 or 3 def view_on_site (self, obj): 4 return 'https: // www.baidu.com'
24. radio_fields: use the radio display option (select is used by FK by default) for detailed pages)
1 radio_fields = {"ug": admin. VERTICAL} # Or admin. HORIZONTAL
25. show_full_result_count = True
1 @admin.register(models.UserInfo)2 class UserAdmin(admin.ModelAdmin):3     # show_full_result_count = True # 1 result (12 total)4     # show_full_result_count = False  # 1 result (Show all)5     search_fields = ('user',)
26. formfield_overrides ={}. When the page is detailed, specify the plug-in
 1 rom django.forms import widgets 2 from django.utils.html import format_html 3   4 class MyTextarea(widgets.Widget): 5     def __init__(self, attrs=None): 6         # Use slightly better defaults than HTML's 20x2 box 7         default_attrs = {'cols': '40', 'rows': '10'} 8         if attrs: 9             default_attrs.update(attrs)10         super(MyTextarea, self).__init__(default_attrs)11  12     def render(self, name, value, attrs=None):13         if value is None:14             value = ''15         final_attrs = self.build_attrs(attrs, name=name)16         return format_html('<textarea {}>\r\n{}</textarea>',final_attrs, value)17  18  19  20 @admin.register(models.UserInfo)21 class UserAdmin(admin.ModelAdmin):22  23     formfield_overrides = {24         models.models.CharField: {'widget': MyTextarea},25     }
27. prepopulated_fields = {}: Add a page. When a field is filled in with a value, the value is automatically filled in the specified field.
1 @ admin. register (models. userInfo) 2 class UserAdmin (admin. modelAdmin): 3 4 prepopulated_fields = {"email": ("user", "pwd",)} 5 6 7 # PS: Using js to implement functions in DjangoAdmin, the value of the email field on the page will be automatically filled when you enter: user and pwd.
28. form = ModelForm, used to customize form verification during user requests
 1 from app01 import models 2 from django.forms import ModelForm 3 from django.forms import fields 4   5   6 class MyForm(ModelForm): 7     others = fields.CharField() 8   9     class Meta:10         model = models = models.UserInfo11         fields = "__all__"12  13 @admin.register(models.UserInfo)14 class UserAdmin(admin.ModelAdmin):15  16     form = MyForm
29. empty_value_display = "when the column data is empty, the default value is displayed"
1 @ admin. register (models. userInfo) 2 class UserAdmin (admin. modelAdmin): 3 empty_value_display = "when the column data is empty," 4 5 list_display = ('user', 'pwd', 'up') 6 7 def up (self, obj): 8 return obj. user9 up. empty_value_display = "when the specified column data is empty, it is displayed by default"

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.