According to the needs of custom admin

Defined list page

Custom list_filter

First, the complete function of the filter, the filter need to customize. Defined above the PostAdmin defined in the following code:

class CategoryOwnerFilter(admin.SimpleListFilter):
    """
    自定义过滤器只展示当前用户分类
    """
    title = '分类过滤器'
    parameter_name = 'owner_category'

    def lookups(self, request, model_admin):
        return Category.objects.filter(owner=request.user).values_list('id', 'name')
    
    def queryset(self, request, queryset):
        category_id = self.value()
        if category_id:
            return queryset.filter(category_id=self.value())
        return queryset

Custom filters implemented by inheriting class Django admin SimpleListFilter provided, then only need to customize the filter configuration to the ModelAdmin.

SimpleListFilter class provides two methods and two properties. When the title for the show title, parameter_name is the name of the URL parameter, such as query classification id query for the content of 1, Query back is part of the URL ?owner_category=1, then you can get the id through the filter, thereby filtering.

lookups: Returns the content to be displayed and used in the query id (Query is used above).

queryset: Back to list page data based on the content of URL Query. For example, if the last Query URL Shi ?owner_category=1, get this self.value()is 1, then it will be filtered according to Queryset 1. Queryset Here is a list of all the pages of data collection show that post data sets.

When you write, you only need to modify list_filter:

list_filter = [CategoryOwnerFilter]

You will be able to allow users to filter the sidebar to see only their own created a classification.

Custom list page data

Finish customizing the list_filter, but also need to continue customizable, allowing the user currently logged in list page see only articles that you have created.

PostAdmin inherited from admin.ModelAdmin, obviously need to see what ModelAdmin provides methods, you can rewrite it.

blog/admin.py:

@admin.register(Post)
class PostAdmin(admin.ModelAdmin):
    list_display = [
        'title', 'category', 'status',
        'created_time', 'owner', 'operator'
    ]
    
    # 省略部分代码
    
    def save_model(self, request, obj, form, change):
        obj.owner = request.user
        return super(PostAdmin, self).save_model(request, obj, form, change)

    def get_queryset(self, request):
        qs = super(PostAdmin, self).get_queryset(request)
        return qs.filter(owner=request.user)

From these two custom can be seen, on the part of the data filtering, just need to find where the data source, which is generated in the final QuerySet, then filtered to.

Edit page of the configuration

First, is the position of the button, the main button is the "Save" in the edit page, but Django provides two buttons for easy operation: "Save and Continue" and "Save and add another." About the position of the button, there is a configuration item can be done: save_on_top used to control whether the display above three buttons at the top of the page.

Field shows whether requirements and display order, or may be configured by fields fieldset. You can specify which fields does not exclude by showing, for example the following owner, the current user is automatically assigned in the program. code show as below:

# blog/admin.py

@admin.register(Post)
class PostAdmin(admin.ModelAdmin):
    # 省略其他代码
    exclude = ('owner', )
    
    fields = (
        ('category', 'title'),
        'desc',
        'status',
        'content',
        'tag',
    )
    # 省略其他代码
    

fields are arranged two functions, one is to define the field of display, other display fields are arranged sequentially.

fieldsets used to control the page layout, it is replaced with the first fields of the above code:

fieldsets = (
    ('基础配置', {
        'description': '基础配置描述', 
        'fields': (
            ('title', 'category'), 
            'status', 
        ), 
    }),
    ('内容', {
        'fields': (
            'desc',
            'content',
        ),
    }),
    ('额外信息', {
        'classes': ('collapse', ),
        'fields': ('tag', ),
    })
)

fieldsets is required format list tuple of two elements, such as:

fieldsets = (
    (名称, {内容}),
    (名称, {内容}),
)

Tuple which contains the contents of two elements, the first element is the name of the current section of the second element is the current section of the description, the field configuration and style. In other words, the first element is a string, the second element is dict, dict and the key may be fields, description and classes.

The configuration of the same fields as above, which can control the display elements, the elements can be sorted and combined to the position of the element. The role of classes is to add some sections to be configured CSS properties, Django admin is supported by default collapse and wide. Of course, you can also write other properties, and then to deal with their own style.

About editing configuration page, as well as for configuration filter_horizontal and filter_vertica1 many-field display, which are used to control the display of results-many fields.

Custom static resources into

CSS and JavaScript can be increased by the resources you want to add a custom class and from the Media page.

class PostAdmin(admin.ModelAdmin):
    class Media:
        css = {
            'all': ("https://cdn.bootcss.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css", ),
        }
        js = ('https://cdn.bootcss.com/bootstrap/4.0.0-beta.2/js/bootstrap.bundle.js', )

Custom Form

All configurations above are based on ModelAdmin, if there are more customized needs, such as article description field can be displayed in a multi-line multi-column mode, which requires the use ModelForm.

Adminforms.py first add a file in the directory of the blog. Because this is used as a back-end management of the Form, so here is named adminforms death rather than forms. This is just to separate area for Form processing of the reception for user input.

Next, the need to write code, which is defined in the Form. On the role of the Form, Form can be said is consistent with the logic of the Model, Model is an abstract fields in the database, user input, and Form is to show the Model of abstract data.

In adminforms.py, the status of this field to customize the display by Form:

from django import forms

class PostAdminForm(forms.ModelForm):
    desc = forms.CharField(widget=forms.Textarea, label='摘要', required=False)

Then its configuration to the admin definition:

# blog/admin.py

from .adminforms import PostAdminForm

class PostAdmin(admin.ModelAdmin):
    form = PostAdminForm
    # 省略其他代码

At this time, refresh the page, you can see article description field has been changed to a Textarea components.

Custom site

A site corresponds to a site, and now there is a new demand: the user management module should be managed separately with the article classification data. In addition, the need to modify the default display background.

url(r'^admin/', admin.site.urls)

Here is an example of site django.contrib.admin.AdminSite therefore, inherit AdminSite can define your own site, the following code:

from django.contrib.admin import AdminSite

class CustomSite(AdminSite):
    site_header = 'Typeidea'
    site_title = 'Typeidea管理后台'
    index_title = '首页'
    
custom_site = CustomSite(name='cus_admin')

The code into typeidea / typeidea / custom_site.py, and then modify the code of the lower part of all App register to PostAdmin Example:

The @admin.register(Post)changed @admin.register(Post, site=custom_site), which requires the introduction of the modulefrom typeidea.custom_site import custom_site

The above is the reverse with a way to get back the address, use the admin name, it is necessary to adjust the blog / admin.py code.

Original code:

def operator(self, obj):
    return format_html(
        '<a href="{}">编辑</a>',
        reverse('admin:blog_post_change', args=(obj.id,))
    )
operator.short_description = '操作'

change into:

def operator(self, obj):
    return format_html(
        '<a href="{}">编辑</a>',
        reverse('cus_admin:blog_post_change', args=(obj.id,))
    )
operator.short_description = '操作'

Next, the file need to be modified in urls.py, the complete code is as follows:

from django.conf.urls import url
from django.contrib import admin

from .custom_site import custom_site

urlpatterns = [
    url(r'^super_admin/', admin.site.urls),
    url(r'^admin/', custom_site)
]

So there is two sets of back-end address, set for managing users, another set used to manage the business. But the two systems are based on a user's system logic, but were divided on the URL.

Guess you like

Origin www.cnblogs.com/qiuxirufeng/p/11391693.html