Djangoadminsite (b) modeladminmethods

Source: Internet
Author: User

Modeladmin methods

Save_model (request, obj, form, change)

This method is the behavior of the admin interface when the model instance is saved by the user. Request is HttpRequest instance, obj is model instance, form is Modelform instance, change is bool value, depending on whether the model instance is new or modified.

Override this method to do some pre-save or post-save behavior.

For example, you can save Request.user as a property of the model instance:

From Django.contrib Import admin

Class Articleadmin (admin. Modeladmin):
def save_model (self, request, obj, form, change):
Obj.user = Request.user
Obj.save ()

Delete_model (Request, obj)

The Admin interface method when the user deletes the model instance.

Save_formset (Request, form, FormSet, change)

Admin Interface User Save FormSet method, can rewrite:

Class Articleadmin (admin. Modeladmin):
def save_formset (self, request, form, FormSet, change):
instances = Formset.save (commit=false)
For instance in instances:
Instance.user = Request.user
Instance.save ()
FORMSET.SAVE_M2M ()

Get_ordering (Request)

Sort.

Class Personadmin (admin. Modeladmin):

def get_ordering (self, request):
If Request.user.is_superuser:
return [' Name ', ' rank ']
Else
return [' Name ']

Get_search_results (Request, Queryset, search_term)

Query results can be customized.

save_related (Request, form, formsets, change)

Formsets is the list of the model's inline formsets. The behavior of the model's related object when it is saved.

def save_related (self, request, form, formsets, change):
"""
Given the ' HttpRequest ', the parent ' modelform ' instance, the
List of inline formsets and a Boolean value based on whether the
Parent is being added or changed, save the related objects to the
Database. Note that at this point Save_form () and Save_model () has
already been called.
"""
FORM.SAVE_M2M ()
For FormSet in Formsets:
Self.save_formset (Request, form, FormSet, Change=change)

Get_readonly_fields (Request, Obj=none)

Returns a read-only field.

Get_prepopulated_fields (Request, Obj=none)

Returns the preset field.

Get_list_display (Request)

Returns List_display.

Get_list_display_links (Request, List_display)

Returns List_display_link.

Get_fields (Request, Obj=none)
Return to fields.

Get_fieldsets (Request, Obj=none)
Returns FieldSets.

Get_list_filter (Request)
Returns List_filter.

Get_search_fields (Request)
Returns Search_fields.

Get_inline_instances (Request, Obj=none)
Returns a list or tuple of Inlinemodeladmin objects

Class Mymodeladmin (admin. Modeladmin):
def get_inline_instances (self, request, Obj=none):
return [Inline (Self.model, self.admin_site) for inline in Self.inlines]

Get_urls ()
Returns the available URLs for modeladmin.

Class Mymodeladmin (admin. Modeladmin):
def get_urls (self):
URLs = Super (mymodeladmin, self). Get_urls ()
My_urls = Patterns ("',
(R ' ^my_view/$ ', Self.my_view)
)
return my_urls + URLs

def my_view (self, request):
# custom view which should return an HttpResponse
Pass

The path to the My_view method above is/admin/myapp/mymodel/my_view/.

However, there are no validations and caches in the example above to provide authentication and caching:

Class Mymodeladmin (admin. Modeladmin):
def get_urls (self):
URLs = Super (mymodeladmin, self). Get_urls ()
My_urls = Patterns ("',
(R ' ^my_view/$ ', Self.admin_site.admin_view (Self.my_view))
)
return my_urls + URLs

If the page can be cached, or if the permission is being verified:

(R ' ^my_view/$ ', Self.admin_site.admin_view (Self.my_view, Cacheable=true))

Get_form (Request, Obj=none, **kwargs)

Returns the Modelform used by add and change view. The following users hide some fields when they are not superuser.

Class Mymodeladmin (admin. Modeladmin):
def get_form (self, request, Obj=none, **kwargs):
Self.exclude = []
If not request.user.is_superuser:
Self.exclude.append (' Field_to_hide ')
Return super (Mymodeladmin, self). Get_form (Request, obj, **kwargs)

Get_formsets (Request, Obj=none)

Yields inlinemodeladmins for use with admin add and change views.

If you only want to show a special inline in the change view:

Class Mymodeladmin (admin. Modeladmin):
Inlines = [Myinline, Someotherinline]

def get_formsets (self, request, Obj=none):
For-Inline in self.get_inline_instances (request, obj):
# Hide Myinline in the Add view
If isinstance (inline, myinline) and obj is None:
Continue
Yield Inline.get_formset (request, obj)

Get_formsets_with_inlines (Request, Obj=none)

Yields (FormSet, inlinemodeladmin) pairs for use with admin add and change views.

If you only want to show a special inline in the change view:

Class Mymodeladmin (admin. Modeladmin):
Inlines = [Myinline, Someotherinline]

def get_formsets_with_inlines (self, request, Obj=none):
For-Inline in self.get_inline_instances (request, obj):
# Hide Myinline in the Add view
If isinstance (inline, myinline) and obj is None:
Continue
Yield Inline.get_formset (request, obj), inline

Formfield_for_foreignkey (Db_field, request, **kwargs)
The default FormField used by the ForeignKey field. Different subsets are returned depending on the user:

Class Mymodeladmin (admin. Modeladmin):
def formfield_for_foreignkey (self, Db_field, request, **kwargs):
if Db_field.name = = "Car":
kwargs["Queryset"] = Car.objects.filter (owner=request.user)
Return super (Mymodeladmin, self). Formfield_for_foreignkey (Db_field, request, **kwargs)

Formfield_for_manytomany (Db_field, request, **kwargs)

Similar to Formfield_for_foreignkey, this method is used for many to many fields.:

Class Mymodeladmin (admin. Modeladmin):
def formfield_for_manytomany (self, Db_field, request, **kwargs):
if Db_field.name = = "Cars":
kwargs["Queryset"] = Car.objects.filter (owner=request.user)
Return super (Mymodeladmin, self). Formfield_for_manytomany (Db_field, request, **kwargs)

Modeladmin.formfield_for_choice_field (Db_field, request, **kwargs)
Similar to Formfield_for_foreignkey and Formfield_for_manytomany, this method is used for choices:

Class Mymodeladmin (admin. Modeladmin):
def formfield_for_choice_field (self, Db_field, request, **kwargs):
if Db_field.name = = "Status":
kwargs[' choices ' = (
(' accepted ', ' accepted '),
(' denied ', ' denied '),
)
If Request.user.is_superuser:
kwargs[' choices ' + = (' ready ', ' ready for Deployment '),)
Return super (Mymodeladmin, self). Formfield_for_choice_field (Db_field, request, **kwargs)

Modeladmin.get_changelist (Request, **kwargs)
Returns the Changelis class used by the Changelist page. Default Django.contrib.admin.views.main.ChangeList.

Modeladmin.get_changelist_form (Request, **kwargs)
Returns the Modelform class used by the Changelist page.

From Django Import forms

Class MyForm (forms. Modelform):
Pass

Class Mymodeladmin (admin. Modeladmin):
def get_changelist_form (self, request, **kwargs):
Return MyForm

Modeladmin.get_changelist_formset (Request, **kwargs)
Returns the Modelformset class used by the Changelist page.

From Django.forms.models import Basemodelformset

Class Myadminformset (Basemodelformset):
Pass

Class Mymodeladmin (admin. Modeladmin):
def get_changelist_formset (self, request, **kwargs):
kwargs[' formset '] = Myadminformset
Return super (Mymodeladmin, self). Get_changelist_formset (Request, **kwargs)

Modeladmin.has_add_permission (Request)
Whether to have add permission.

Modeladmin.has_change_permission (Request, Obj=none)
Whether you have change permissions.

Modeladmin.has_delete_permission (Request, Obj=none)
Whether to have delete permission.

Modeladmin.get_queryset (Request)
Returns the model Queryset set that the admin interface can edit. Different results are returned depending on the user:

Class Mymodeladmin (admin. Modeladmin):
def get_queryset (self, request):
QS = Super (Mymodeladmin, self). Get_queryset (Request)
If Request.user.is_superuser:
Return QS
Return Qs.filter (Author=request.user)

Modeladmin.message_user (Request, message, Level=messages.info, extra_tags= ", Fail_silently=false)
Send a message to a user who is using django.contrib.messages backend.

Modeladmin.get_paginator (Queryset, Per_page, orphans=0, Allow_empty_first_page=true)
Returns a paged instance. Returns an instance of the Paginator to use for this view. By default, instantiates an instance of Paginator.

Modeladmin.response_add (Request, obj, Post_url_continue=none)
Determines that the Httpresponse,model of Add_view () is created and runs.

Modeladmin.response_change (Request, obj)
Determines that the Httpresponse,model of Change_view () is modified to run.

Modeladmin.response_delete (Request, Obj_display)
Determines that the Httpresponse,model of Delete_view () is deleted and then runs.

Obj_display is the name of the deleted object.

Modeladmin.get_changeform_initial_data (Request)
A hook for the initial data in admin change forms. By default, the fields is given initial values from GET parameters. For instance,? Name=initial_value would set the Name field ' s initial value to be initial_value.

This method should return a dictionary in the form {' fieldname ': ' Fieldval '}:

def get_changeform_initial_data (self, request):
return {' name ': ' Custom_initial_value '}

Other methods

Modeladmin.add_view (Request, form_url= ", Extra_context=none)
Django view for the Model instance addition page. See note below.

Modeladmin.change_view (Request, object_id, form_url= ", Extra_context=none)
Django view for the Model instance Edition page. See note below.

Modeladmin.changelist_view (Request, Extra_context=none)
Django view for the model instances change List/actions page. See note below.

Modeladmin.delete_view (Request, object_id, Extra_context=none)
Django view for the model instance (s) deletion confirmation page. See note below.

Modeladmin.history_view (Request, object_id, Extra_context=none)
Django view for the page is shows the modification history for a given model instance.

These 5 methods are actually set to the Django view method. Can be refactored, typically adding the context data of the template used to render the view:

Class Mymodeladmin (admin. Modeladmin):

# A template for A very customized change view:
change_form_template = ' admin/myapp/extras/openstreetmap_change_form.html '

def get_osm_info (self):
# ...
Pass

def change_view (self, request, object_id, form_url= ", Extra_context=none):
Extra_context = Extra_context or {}
extra_context[' osm_data '] = Self.get_osm_info ()
Return super (Mymodeladmin, self). Change_view (Request, OBJECT_ID,
Form_url, Extra_context=extra_context)

Modeladmin Asset Definitions

Add JS and CSS to Modeladmin's add/change views:

Class Articleadmin (admin. Modeladmin):
Class Media:
CSS = {
"All": ("My_styles.css",)
}
JS = ("My_code.js",)

Adding custom validation to the admin

Custom form:

Class Myarticleadminform (forms. Modelform):
def clean_name (self):
# do something, that validates your data
return self.cleaned_data["name"]
Class Articleadmin (admin. Modeladmin):
form = Myarticleadminform

The above is Djangoadminsite (ii) Modeladminmethods content, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!

  • Related Article

    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.