0

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

tschm
  • 2,905
  • 6
  • 33
  • 45
  • 2
    You can raise an exception and catch it in your view. We cannot say much without seeing your view code. Also, you **overridden** the save method, not **overwritten** it. – Selcuk Apr 01 '15 at 12:26
  • I haven't written any to be honest. This all takes place in the standard admin interface. – tschm Apr 01 '15 at 12:28
  • Usually you are not overwriting `save()` but `clean()` instead. See https://docs.djangoproject.com/en/1.7/ref/models/instances/#django.db.models.Model.clean for details. – Klaus D. Apr 01 '15 at 12:29
  • 1
    Maybe this [post](http://stackoverflow.com/questions/8771029/django-raise-a-validation-error-in-a-models-save-method) could help you. – Salvatore Avanzo Apr 01 '15 at 12:34
  • I am a bit surprised that this is as complicated as it seems. Django seems to solve problems at the cost of introducing new ones. For now I have overridden (thank you @Selcuk) the save_model in the class inherited from model.AdminModel. This gives me access to Django's message framework. At least I can now post a message that the object did not pass validation but then a second messages shows up that it has been stored successfully (although that's a red herring). – tschm Apr 02 '15 at 07:51

0 Answers0