0

This question is connected to this one: Django - disable model editing

This is my code:

    def save(self, *args, **kwargs):
        if self.pk is None:
            print "THIS IS ADD ACTION. NOT DELETE OR CHANGE !!!"

            numberOfAvalableBooks = Book.objects.get(id=self.book.id).amount
            print 'numberOfAvalableBooks %s' % numberOfAvalableBooks

            if self.get_action_display() == 'Out':
                if numberOfAvalableBooks - self.amount < 0:
                    return "YOU DO NOT HAVE ENOUGH BOOKS !!!"

            super(Transaction, self).save(*args, **kwargs)

            # UPDATE AMOUNT
            book = Book.objects.get(id=self.book.id)

            if self.get_action_display() == 'Out':
                book.amount -= self.amount
            elif self.get_action_display() == 'In':
                book.amount += self.amount
            else:
                print "UNKNOWN ACTION !!!"

            book.save()
        else:
            print self.pk
            return "CHANGE ACTION DISABLED !!!"

This is working fine, no update or delete is possible.
What I do not like is that after clicking "Save" button I still have yellow message with "The ….. was added successfully.".

Is it possible and how, to replace that message, and make it with different color ?

Thanks

Community
  • 1
  • 1
WebOrCode
  • 6,852
  • 9
  • 43
  • 70

1 Answers1

1

Overwirte the response_add(self, request, obj, post_url_continue=None) method of your admin class.

Have a look on the original ModelAdmin.response_add in django/contrib/admin/options.py

Here is a very basic example of a model admin that overwrites the messages after adding and changing instances.

class AmodelAdmin(admin.ModelAdmin):
    ...
    def response_add(self, request, obj, post_url_continue=None):
        from django.core.urlresolvers import reverse
        msg = "DON'T CLICK THIS BUTTON!"
        self.message_user(request, msg, level=messages.WARNING)
        return self.response_post_save_add(request, obj)

    def response_change(self, request, obj):)
        msg = "DON'T CLICK THIS BUTTON!"
        self.message_user(request, msg, level=messages.WARNING)
        return self.response_post_save_change(request, obj)
kanu
  • 726
  • 5
  • 9
  • I have edited you response_change method to suite my need. Also you had BUG, you did not imported messages. Thanks on your help. – WebOrCode Dec 11 '13 at 13:34