Wednesday, April 27, 2011

Customization of django's admin app



Customization of django's admin app


Strategies:

  1. Use the normal ModelAdmin options (actions, exclude, fields, etc)
  2. User ModelAdmin media
  3. Extend/override ModelAdmin templates
  4. Create custom views / templates (sometimes it’s easier to create a custom view than hack de admin app)
  5. Hack ModelAdmin / ModelForm

Adding custom validation to the admin

Create a custom form based on forms.ModelForm and use it with ModelAdmin.form.

[link]

Creating a custom form based on forms.ModelForm

Changing the widget for a field

from django.forms import ModelForm, Textareaclass AuthorForm(ModelForm):
class Meta:
model
= MyModel
fields
= ('name', 'title', 'birth_date')
widgets
= {
'name': Textarea(attrs={'cols': 80, 'rows': 20}),
}

Further customizating a field (type, label, etc)

class ArticleForm(ModelForm):
pub_date
= MyDateFormField(label='Publication date')

name = TextField(widget=forms.TextField)
class Meta:
model
= MyModel

Changing the widget for a particular field

Reusing some of admin’s widget for my form

links:

  1. Django multi-select widget?

Changing the Widget for a class of Fields

ModelAdmin.formfield_overrides = { ... }

Creating custom widgets

links:

  1. Custom fields and widgets for Django forms

Templates that can be overriden per app/per model

  1. app_index.html
  2. change_form.html
  3. change_list.html
  4. delete_confirmation.html
  5. object_history.html

Overriding admin templates

Copy some template from:

django/contrib/admin/templates/admin

(for example change_form.html)

put it in any of these

  1. "admin/%s/%s/change_form.html" % (app_label, opts.object_name.lower())
  2. "admin/%s/change_form.html" % app_label
  3. "admin/change_form.html"

in your TEMPLATE_DIRS.

Replacing default templates used by ModelAdmin views

  1. ModelAdmin.add_form_template (for add_view() )
  2. ModelAdmin.change_form_template (for change_view() )
  3. ModelAdmin.change_list_template (for changelist_view() )
  4. ModelAdmin.delete_confirmation_template(for delete_view() )
  5. ModelAdmin.delete_selected_confirmation_template
  6. ModelAdmin.object_history_template (for history_view() )

Changing the context data provided to the templates above

Override

  1. ModelAdmin.add_view
  2. ModelAdmin.change_view
  3. ModelAdmin.changelist_view
  4. ModelAdmin.delete_view
  5. ModelAdmin.history_view

Using different admin sites

Doing this allows you to have several admin sites suited to different needs.

In particular, the index_template and login_form can be overriden:

AdminSite.index_template

AdminSite.login_template

Adding views to admin sites

TODO

No comments:

Post a Comment