41)django-admin

一:介绍

  通过django admin可以快速生成后台管理功能。

二:设置

  工程同名下settings.py

  1)在INSTALLED_APPS中增加django.contrib.admin

  2)在INSTALLED_APPS 中增加

    django.contrib.auth

    django.contrib.contenttypes

    django.contrib.messages

    django.contrib.sessions

    django.contrib.admin依赖上面包

  3)在context_processors中

    django.contrib.auth.context_processors.auth

    django.contrib.messages.context_processors.messages

   在MIDDLEWARE,TEMPLATES中增加

    django.contrib.auth.middleware.AuthenticationMiddleware

    django.contrib.messages.middleware.MessageMiddleware

  上面都是默认配置好的

  4)在INSTALLED_APPS中增加自己的应用

  5)创建ModelAdmin

  6)ModelAdmin注册到AdminSite

  7)urls.py中配置

        from django.contrib import admin
        admin.autodiscover()
        # And include this URLpattern...
        urlpatterns = patterns('',
        # ...
        (r'^admin/', include(admin.site.urls)),
        # ...
        )
View Code

 三:ModelAdmin

  ModelAdmin是admin接口,在app下面建立admin.py

  示例

方式1:可以定制显示
from django.contrib import admin
from myproject.myapp.models import Author

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

方式2:默认
from django.contrib import admin
from myproject.myapp.models import Author

admin.site.register(Author)

四:ModelAdmin常用选项

  1)model action

    ModelAdmin.actions 

    ModelAdmin.actions_on_top #处理动作在上面显示

    ModelAdmin.actions_on_bottom 处理动作在下面显示#默认(actions_on_top True; actions_on_bottom False).

    ModelAdmin.actions_selection_counter #动作列表select来显示 默认(actions_selection_counter True)

  2)ModelAdmin.date_hierarchy 处理日期类型DateField or DateTimeField 添加和修改数据会显示下拉日期

   示例:  

date_hierarchy = 'pub_date'
date_hierarchy = 'author__pub_date' #author类下的pub_date字段

  3)ModelAdmin.empty_value_display 空值或者None 显示

from django.contrib import admin

class AuthorAdmin(admin.ModelAdmin):
    empty_value_display = '-empty-'


from django.contrib import admin

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

    def view_birth_date(self, obj):
        return obj.birth_date

    view_birth_date.empty_value_display = '???'
View Code

  4)ModelAdmin.exclude 不显示的字段 

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

  5)ModelAdmin.fields 增加或者编辑时显示的字段  

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

  6)ModelAdmin.fieldsets 增加或者编辑页面显示组 

from django.contrib import admin

class FlatPageAdmin(admin.ModelAdmin):
    fieldsets = (
        (None, {
            'fields': ('url', 'title', 'content', 'sites')
        }),
        ('Advanced options', {
            'classes': ('collapse',),
            'fields': ('registration_required', 'template_name'),
        }),
    )
View Code

  7)ModelAdmin.filter_horizontal ,ModelAdmin.filter_vertical 多对多关系水平多选select

  8)ModelAdmin.list_display  列表数据显示的列  

#方式1
class PersonAdmin(admin.ModelAdmin):
    list_display = ('first_name', 'last_name')

#方式2
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'

#方式3
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')
View Code

   备注:  1.ForeignKey显示的__str__中的内容

      2 .ManyToManyField 不直接支持,需要自定义方法显示

      3. BooleanField  NullBooleanField 会显示on,off代替True,False

      4. 显示内容有html,需要在model中实现format_html()方法  

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(
            '<span style="color: #{};">{} {}</span>',
            self.color_code,
            self.first_name,
            self.last_name,
        )

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

  9)ModelAdmin.list_display_links 那些字段点击进入编辑页面(字段必须在list_display中)

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

  10)ModelAdmin.list_editable 增加或者编辑多行编辑text

  11)ModelAdmin.list_filter 数据列表中的过滤字段,支持BooleanFieldCharFieldDateFieldDateTimeFieldIntegerFieldForeignKey or ManyToManyField

class PersonAdmin(admin.ModelAdmin):
    list_filter = ('is_staff', 'company')

a class inheriting from django.contrib.admin.SimpleListFilter, which you need to provide the title and parameter_name attributes to and override the lookups and queryset methods, e.g.:

from datetime import date

from django.contrib import admin
from django.utils.translation import gettext_lazy as _

class DecadeBornListFilter(admin.SimpleListFilter):
    # Human-readable title which will be displayed in the
    # right admin sidebar just above the filter options.
    title = _('decade born')

    # Parameter for the filter that will be used in the URL query.
    parameter_name = 'decade'

    def lookups(self, request, model_admin):
        """
        Returns a list of tuples. The first element in each
        tuple is the coded value for the option that will
        appear in the URL query. The second element is the
        human-readable name for the option that will appear
        in the right sidebar.
        """
        return (
            ('80s', _('in the eighties')),
            ('90s', _('in the nineties')),
        )

    def queryset(self, request, queryset):
        """
        Returns the filtered queryset based on the value
        provided in the query string and retrievable via
        `self.value()`.
        """
        # Compare the requested value (either '80s' or '90s')
        # to decide how to filter the queryset.
        if self.value() == '80s':
            return queryset.filter(birthday__gte=date(1980, 1, 1),
                                    birthday__lte=date(1989, 12, 31))
        if self.value() == '90s':
            return queryset.filter(birthday__gte=date(1990, 1, 1),
                                    birthday__lte=date(1999, 12, 31))

class PersonAdmin(admin.ModelAdmin):
    list_filter = (DecadeBornListFilter,)
View Code

  注:

    1.django.contrib.admin.FieldListFilter

    2. RelatedOnlyFieldListFilter

  

a tuple, where the first element is a field name and the second element is a class inheriting from django.contrib.admin.FieldListFilter, for example:

class PersonAdmin(admin.ModelAdmin):
    list_filter = (
        ('is_staff', admin.BooleanFieldListFilter),
    )
You can limit the choices of a related model to the objects involved in that relation using RelatedOnlyFieldListFilter:

class BookAdmin(admin.ModelAdmin):
    list_filter = (
        ('author', admin.RelatedOnlyFieldListFilter),
    )
View Code

  12)ModelAdmin.list_max_show_all 数据列表,最多显示多少行(总行),默认200行

  13)ModelAdmin.list_per_page 数据列表每页显示多少行

  14)ModelAdmin.list_select_related 

  

class ArticleAdmin(admin.ModelAdmin):
    list_select_related = ('author', 'category')
will call select_related('author', 'category').

If you need to specify a dynamic value based on the request, you can implement a get_list_select_related() method.
View Code

  15)ModelAdmin.ordering 数据列表,排序字段

   16)ModelAdmin.radio_fields django 默认显示的是choice,可以修改成radio

  

class PersonAdmin(admin.ModelAdmin):
    radio_fields = {"group": admin.VERTICAL}
You have the choice of using HORIZONTAL or VERTICAL from the django.contrib.admin module.

Don’t include a field in radio_fields unless it’s a ForeignKey or has choices set.
View Code

  17) ModelAdmin.raw_id_fields django默认ForeignKey显示的是select,可以修改成input搜索

  

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

  18)ModelAdmin.readonly_fields 不可编辑字段,django默认是可以编辑的

  19)ModelAdmin.search_fields  数据列表 可以搜索的字段

可以是char,text,也可以是foreignkey,manytomany,

search_fields = ['foreign_key__related_fieldname']

四:ModelAdmin常用方法

  1)ModelAdmin.save_model 

from django.contrib import admin

class ArticleAdmin(admin.ModelAdmin):
    def save_model(self, request, obj, form, change):
        obj.user = request.user
        super().save_model(request, obj, form, change)
View Code

  2)ModelAdmin.delete_model

  3)ModelAdmin.save_formset

class ArticleAdmin(admin.ModelAdmin):
    def save_formset(self, request, form, formset, change):
        instances = formset.save(commit=False)
        for obj in formset.deleted_objects:
            obj.delete()
        for instance in instances:
            instance.user = request.user
            instance.save()
        formset.save_m2m()
View Code

  4)ModelAdmin.get_ordering(request)

class PersonAdmin(admin.ModelAdmin):

    def get_ordering(self, request):
        if request.user.is_superuser:
            return ['name', 'rank']
        else:
            return ['name']
View Code

  5)ModelAdmin.get_search_results

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

    def get_search_results(self, request, queryset, search_term):
        queryset, use_distinct = super().get_search_results(request, queryset, search_term)
        try:
            search_term_as_int = int(search_term)
        except ValueError:
            pass
        else:
            queryset |= self.model.objects.filter(age=search_term_as_int)
        return queryset, use_distinct
View Code

五:ModelAdmin可以自定义模板

  ModelAdmin.add_form_template  add_view()

  ModelAdmin.change_form_template  change_view()

  ModelAdmin.change_list_template  changelist_view()

  ModelAdmin.delete_confirmation_template  delete_view()

  ModelAdmin.delete_selected_confirmation_template delete_selected

  ModelAdmin.object_history_template history_view()

  odelAdmin.popup_response_template response_add()response_change(), and response_delete()

  

原文地址:https://www.cnblogs.com/lixiang1013/p/8051943.html