Home:ALL Converter>Overwriting the save method of a Django model

Overwriting the save method of a Django model

Ask Time:2015-04-01T20:22:47         Author:tschm

Json Formatter

I have a table of symbols. Before I add a new symbol I validate the symbol.

For this purpose I have overwritten the save method in the model:

def save(self, *args, **kwargs):

    if self.check_exist(self.name):
        # Call the "real" save() method.
        super(AssetsSymbol, self).save(*args, **kwargs)    
    else:
        # Yes, the symbol is not saved in the database
        # That's good.

Using now one or two lines of code in else how can I inform the user that he has submitted an invalid symbol?

Django still reports that the symbol "TEST" has been saved (which is very misleading)

I try to avoid using Modelforms etc.

Here's a more current implementation:

@admin.register(AssetsSymbol)
class AssetSymbolAdmin(admin.ModelAdmin):
    list_display = ("name", "group", "alive", "internal")
    list_filter = ("name", "group", "alive", "internal")

    ...
    def save_model(self, request, obj, form, change):
        if self.check_exist(obj.name):
            messages.add_message(request, messages.SUCCESS, 'Valid Bloomberg Symbold {0}'.format(obj.name))
            obj.save()
        else:
            messages.add_message(request, messages.ERROR, 'Invalid Bloomberg Symbol {0}'.format(obj.name))

The message Invalid Bloomberg Symbol is displayed correctly but followed by a message that the symbol has been stored!?

Author:tschm,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/29390750/overwriting-the-save-method-of-a-django-model
yy