Django admin site (1) ModelAdmin Options, djangomodeladmin
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:
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>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>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.
Why can I only use django-adminpy startproject IN THE Python27 \ Lib \ site-packages \ django \ bin directory?
You can try
"C: \ Python27; C: \ Python27 \ Scripts;" add to path, so that you do not have to add everything installed in the site-packages directory to path separately.
After entering Django-adminpy startproject mysite in django, no new project is created and no response is made. How can this problem be solved?
When django is installed normally,
Check whether there are permissions and whether there are hidden folders with the same name.
Django-admin.py startproject mysite> 1.txt, see the Log