Skip to content Skip to sidebar Skip to footer

Django Admin, Custom Error Message?

I would like to know how to show an error message in the Django admin. I have a private user section on my site where the user can create requests using 'points'. A request takes 1

Solution 1:

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

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

classMyForm(forms.ModelForm):
    classMeta:
        model = MyModel
    defclean_points(self):
        points = self.cleaned_data['points']
        if points.isdigit() and points < 1:
            raise forms.ValidationError("You have no points!")
        return points

classMyModelAdmin(admin.ModelAdmin):
    form = MyForm

admin.site.register(MyModel, MyModelAdmin)

Hope that helps!

Solution 2:

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

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

See the documentation.

Solution 3:

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

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

Post a Comment for "Django Admin, Custom Error Message?"