Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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

like image 590
Asinox Avatar asked Sep 02 '09 19:09

Asinox


1 Answers

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!

like image 89
Gabriel Hurley Avatar answered Sep 28 '22 05:09

Gabriel Hurley