[ACCEPTED]-Django admin, custom error message?-django-admin

Accepted answer
Score: 21

One way to do that is by overriding the 4 ModelForm for the admin page. That allows 3 you to write custom validation methods and 2 return errors of your choosing very cleanly. Like 1 this in admin.py:

from django.contrib import admin
from models import *
from django import forms

class MyForm(forms.ModelForm):
    class Meta:
        model = MyModel
    def clean_points(self):
        points = self.cleaned_data['points']
        if points.isdigit() and points < 1:
            raise forms.ValidationError("You have no points!")
        return points

class MyModelAdmin(admin.ModelAdmin):
    form = MyForm

admin.site.register(MyModel, MyModelAdmin)

Hope that helps!

Score: 5

I've used the built-in Message system for 5 this sort of thing. This is the feature 4 that prints the yellow bars at the top of 3 the screen when you've added/changed an 2 object. You can easily use it yourself:

request.user.message_set.create(message='Message text here')

See 1 the documentation.

Score: 2

Django versions < 1.2 https://docs.djangoproject.com/en/1.4/ref/contrib/messages/

from django.contrib import messages
messages.add_message(request, messages.INFO, 'Hello world.')


More Related questions