[Solved]-Django admin, custom error message?

21πŸ‘

βœ…

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!

5πŸ‘

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.

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.')
πŸ‘€zzart

Leave a comment