Django admin site (1) modeladmin options

Source: Internet
Author: User

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:

  1. Add 'django. contrib. admin' to the installed_apps configuration of setting.
  2. Ensure that installed_apps contains 'django. contrib. auth ', 'django. contrib. contenttypes ', 'django. contrib. messages 'and 'django. contrib. sessions. ', Django admin requires these four packages.
  3. 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)
  4. Determine which models need to be applied to the admin.
  5. Create a modeladmin for admin. py in the app that requires admin.
  6. Register model and modeladmin
    from django.contrib import adminfrom myproject.myapp.models import Authorclass AuthorAdmin(admin.ModelAdmin):    passadmin.site.register(Author, AuthorAdmin)
  7. Configure admin access in urlconf
    from django.contrib import adminadmin.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 adminfrom .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 adminfrom .models import Author, Reader, Editorfrom 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 ().

ClassApps. 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 adminclass 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 adminclass FlatPageAdmin(admin.ModelAdmin):    fieldsets = (        (None, {            ‘fields‘: (‘url‘, ‘title‘, ‘content‘, ‘sites‘)        }),        (‘Advanced options‘, {            ‘classes‘: (‘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 formsfrom django.contrib import adminfrom myapp.models import Personclass 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 modelsfrom django.contrib import admin# Import our custom widget and our model from where they‘re definedfrom myapp.widgets import RichTextEditorWidgetfrom myapp.models import MyModelclass 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 %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 a model, similar to a callable function.
    from django.db import modelsfrom django.contrib import adminclass 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 modelsfrom django.contrib import adminfrom django.utils.html import format_htmlclass 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: #{0};">{1} {2}</span>‘,                           self.color_code,                           self.first_name,                           self.last_name)    colored_name.allow_tags = Trueclass 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 modelsfrom django.contrib import adminclass 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 = Trueclass PersonAdmin(admin.ModelAdmin):    list_display = (‘name‘, ‘born_in_fifties‘) 
  • 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 modelsfrom django.contrib import adminfrom django.utils.html import format_htmlclass 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(‘<span style="color: #{0};">{1}</span>‘,                           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 adminfrom django.utils.html import format_html_joinfrom django.utils.safestring import mark_safeclass 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/>‘),            ‘{0}‘,            ((line,) for line in instance.get_full_address()),        ) or "<span class=‘errors‘>I can‘t determine this address.</span>"    # 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.

 

Django admin site (1) modeladmin options

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.