| | 538 | Adding custom validation to the admin |
|---|
| | 539 | ------------------------------------- |
|---|
| | 540 | |
|---|
| | 541 | Adding custom validation of data in the admin is quite easy. The automatic |
|---|
| | 542 | admin interfaces reuses the Django `forms`_ module. The ``ModelAdmin`` class |
|---|
| | 543 | gives you the ability define your own form:: |
|---|
| | 544 | |
|---|
| | 545 | class ArticleAdmin(admin.ModelAdmin): |
|---|
| | 546 | form = MyArticleAdminForm |
|---|
| | 547 | |
|---|
| | 548 | ``MyArticleAdminForm`` can be defined anywhere as long as you import where |
|---|
| | 549 | needed. Now within your form you can add your own custom validation for |
|---|
| | 550 | any field:: |
|---|
| | 551 | |
|---|
| | 552 | class MyArticleAdminForm(forms.ModelForm): |
|---|
| | 553 | def clean_name(self): |
|---|
| | 554 | # do something that validates your data |
|---|
| | 555 | return self.cleaned_data["name"] |
|---|
| | 556 | |
|---|
| | 557 | It is important you use a ``ModelForm`` here otherwise things can break. See |
|---|
| | 558 | the `forms`_ documentation on `custom validation`_ for more information. |
|---|
| | 559 | |
|---|
| | 560 | .. _forms: ../forms/ |
|---|
| | 561 | .. _custom validation: ../forms/#custom-form-and-field-validation |
|---|
| | 562 | |
|---|