Home >Backend Development >Python Tutorial >Djangoadminsite(二)ModelAdminmethods
ModelAdmin methods
save_model(request, obj, form, change)
This method is the behavior when saving model instances for admin interface users. request is an HttPRequest instance, obj is a model instance, form is a ModelForm instance, and change is a bool value, depending on whether the model instance is new or modified.
Overriding this method can do some pre-save or post-save actions.
For example, you can save request.user as an attribute 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)
Method when the admin interface user deletes the model instance.
save_formset(request, form, formset, change)
The method for admin interface users to save formset can be rewritten:
class ArticleAdmin(admin.ModelAdmin):
def save_formset(self, request, form, formset, change):
instances = formset.save(commit=False)
’s ’s ’ s ’ s ‐ ‐ ‐ ‐ ‐ ‐ ‐ ‐ ‐ ‐ 1
get_ordering(request)
Ordering.
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)
You can customize the query results.
save_related(request, form, formsets, change)
formsets is a list of inline formsets of the model. Behavior when saving model-related objects.
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() have already been called.
"""
form.save_m2m()
for formset in FormSets:
Self.save_formSet (request, form, formset, Change = Change)
Get_reamonly_fields (request, obj = None)
Return to read only fields.
Return fields.
get_fieldsets(request, obj=None)
Return fieldsets.
get_list_filter(request)
get_search_fields(request)
get_inline_instances(request, obj=None)
class MyModelAdmin(admin.ModelAdmin):
return [inline(self.model , self.admin_site) for inline in self.inlines]
get_urls()
Returns the available urls of ModelAdmin. YClass mymodeladmin (admin.modeladmin):
def get_urls (seld):
urls = super (mymodeladmin, self) .Get_Urls ()
(R'^m y_View/$ ', Self. My_View
)
DEF My_view (Self, Request):
# CUSTOM VIEW Whied Return An httpresponse
Pass
The path of my_View method is/admin /MyAPP/MyModel/My_view/.
However, there is no verification and caching in the above example. Verification and caching must be provided:
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 and permissions are still required:
(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 views. Some fields will be hidden when the user below is 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 in admin add and change views.
if Just 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): set(request, obj)
get_formsets_with_inlines(request, obj= None)
Yields (FormSet, InlineModelAdmin) pairs for use in admin add and change views.
If you only want to display 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 isin stance(inline, MyInline) and obj is None:
continue
to yield inline.get_formset(request, obj), inline
formfield_for_foreignkey(db_field, request, **kwargs)
The default formfield used by the Foreignkey field. Returns different subsets according to different users:
def formfield_for_foreignkey(self, db_field, request, **kwargs):
if db_field.name == "car":
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 For choices:
def formfield_for_choice_field(self, db_field, request, **kwargs):
if db_field.name == "status":
('accepted', 'Accepted'),
('denied', 'Denied'),
using using using using using through through through through out through out through out through through off ’ s ’ ’ s ’ through ’ s ’ through ‐ ‐ ‐ ‐ ‐ ‐ ('denied', 'Denied'),
to be ('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. The default is 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)
Return 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)
是否具有add权限。
ModelAdmin.has_change_permission(request, obj=None)
Whether it has change permission.
ModelAdmin.has_delete_permission(request, obj=None)
Whether it has delete permission.
ModelAdmin.get_queryset(request)
Returns the editable model QuerySet set in the admin interface. Returns different results according to different users:
class MyModelAdmin(admin.ModelAdmin):
def get_queryset(self, request):
qs = super(MyModelAdmin, self).get_queryset(request)
if request.user.is_superuser:
using django.contrib.messages backend users send messages.
ModelAdmin.get_paginator(queryset, per_page, orphans=0, allow_empty_first_page=True)
ModelAdmin.response_add(request, obj, post_url_continue=None)
ModelAdmin.response_change(request, obj)
ModelAdmin.response_delete(request, obj_display)
obj_display is the name of the deleted object.
ModelAdmin.get_changeform_initial_data(request)
A hook for the initial data on admin change forms. By default, fields are given initial values from GET parameters. For instance, ?name=initial_value will 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'}
ModelAdmin .add_view(request, form_url='', extra_context=None)
Django view for the model instance addition page. 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. extra_context=None)Django view for the model instance(s) deletion confirmation page. Model instance.
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):
Extra_context['osm_data '] = self.get_osm_info()
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 the content of Djangoadminsite (2) ModelAdminmethods. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!