views:

964

answers:

2

Hi guys, 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 or 2 points from the user's account (depending on the two type of request), so if the account has 0 points the user cant make any requests... in the private user section all this is fine, but the user can also call the company and make a request by phone, and in this case I need the admin to show a custom error message in the case of the user points being 0.

Any help will be nice :)

Thanks guys

+2  A: 

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.

Daniel Roseman
For an error message, form validation is a better option (see Gabriel's answer).
Carl Meyer
Agree, but I didn't think it was clear from the OP whether it was a form. On rereading, you're probably right, but this is a useful technique anyway.
Daniel Roseman
Note: this method worked for Django versions < 1.2. In 1.2 the messages framework changed. The documentation link there links to the development version docs rather than, say, the static 1.1 docs, so now it's inconsistent with the code above. It'd probably be worth updating either code snippet or the docs link, whichever you prefer.
Gabriel Hurley
Thanks Gabriel, I've updated the link.
Daniel Roseman
+8  A: 

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

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!

Gabriel Hurley