Django admin site (2) ModelAdmin methods, djangomodeladmin

Source: Internet
Author: User

Django admin site (2) ModelAdmin methods, djangomodeladmin
ModelAdmin methods

Save_model (request, obj, form, change)

This method is used when the admin interface saves the model instance. 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 added or modified.

Override this method to perform some pre-save or post-save actions.

For example, you can save request. user as the attribute of the model instance:

from django.contrib import adminclass ArticleAdmin(admin.ModelAdmin):    def save_model(self, request, obj, form, change):        obj.user = request.user        obj.save()

Delete_model (request, obj)

Admin interface.

Save_formset (request, form, formset, change)

The admin interface allows you to save the formset method, which can be rewritten:

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)

You can customize the query results.

Save_related (request, form, formsets, change)

Formsets is the list of model inline formsets. The behavior of the model 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() have        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)

The preset fields are returned.

Get_list_display (request)

List_display is returned.

Get_list_display_links (request, list_display)

List_display_link is returned.

Get_fields (request, obj = None)
Return fields.

Get_fieldsets (request, obj = None)
Return fieldsets.

Get_list_filter (request)
List_filter is returned.

Get_search_fields (request)
Returns search_fields.

Get_inline_instances (request, obj = None)
Returns the list or tuples of the InlineModelAdmin object.

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 of 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 above my_view method path is/admin/myapp/mymodel/my_view /.

In the preceding example, verification and cache are not 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, you still need to perform permission Verification:

(r'^my_view/$', self.admin_site.admin_view(self.my_view, cacheable=True))

Get_form (request, obj = None, ** kwargs)

Return the ModelForm used by add and change view. The following fields are hidden when the user is not a 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 you only want to display 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 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 isinstance(inline, MyInline) and obj is None:                continue            yield inline.get_formset(request, obj), inline

Formfield_for_foreignkey (db_field, request, ** kwargs)
The Foreignkey field uses the default formfield. different subsets are returned based on different users:

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)

This method is similar to formfield_for_foreignkey .:

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)
Return the Changelis class used on the changelist page. The default value is django. contrib. admin. views. main. ChangeList.

ModelAdmin. get_changelist_form (request, ** kwargs)
Return the ModelForm class used on the changelist page.

from django import formsclass MyForm(forms.ModelForm):    passclass MyModelAdmin(admin.ModelAdmin):    def get_changelist_form(self, request, **kwargs):        return MyForm

ModelAdmin. get_changelist_formset (request, ** kwargs)
Return the ModelFormSet class used on the changelist page.

from django.forms.models import BaseModelFormSetclass MyAdminFormSet(BaseModelFormSet):    passclass 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 the add permission.

ModelAdmin. has_change_permission (request, obj = None)
Whether to have the change permission.

ModelAdmin. has_delete_permission (request, obj = None)
Whether the account has the delete permission.

ModelAdmin. get_queryset (request)
Return the Editable model QuerySet set in the admin interface. Different results are returned based on different users:

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 messages to users who use django. contrib. messages backend.

ModelAdmin. get_paginator (queryset, per_page, orphans = 0, allow_empty_first_page = True)
Returns a paging 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)
Determine the HttpResponse of add_view () and run the model after it is created.

ModelAdmin. response_change (request, obj)
The HttpResponse of change_view () is determined and runs after the model is modified.

ModelAdmin. response_delete (request, obj_display)
Determine the HttpResponse of delete_view () and run the model after it is deleted.

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 shoshould 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 that shows the modification history for a given model instance.

These five methods are actually set to django's view method. It can be reconstructed. It is generally used to add context data of the template used for rendering 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 for add/change views of ModelAdmin:

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

  


In django admin, where is the url controlled?

In the root urls. py file, include the admin URL

I think the django admin page is ugly. I want to rewrite some pages to overwrite them. Where should I put these pages?

Is it here?
Python27 \ Lib \ site-packages \ django \ contrib \ admin \ templates \ admin
 

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.