0

I am checking if a model instance already exists and if does I want to send a message saying "Name already exists". As there is not request in def save(), is there any other way to send a message via Django message framework or something else??

def save(self, *args, **kwargs):
    self.name = self.name
    if Name.names.name_exists(self.name):
        message = "You already have this name!" # want to send this message
        print("not created")
    else:
        print("created")
        super(Name, self).save(*args, **kwargs)
Max Will
  • 258
  • 2
  • 10
  • I think that you don't need to check if a object name exist by override the save method. Instead, you can check it before create a new object like : `myObject = Object.objects.get(name=name_to_check)` if the object exist then send a message with django message (`from django.contrib import messages`). If not create the new object. – Rvector Sep 02 '21 at 10:36
  • Overriding the save method is not the best practice you mean? – Max Will Sep 02 '21 at 12:42
  • 1
    For this specific goal, yes overriding the save method is not the best idea (i think). You want check if object exist before save. Then do it before call `.save()` on your `object`. – Rvector Sep 02 '21 at 13:31

1 Answers1

1

Yes you can use django messages framework with messages.warning(request, 'Object already exists.') instead of that print statement and depending on your logic instead of warning message you can send success or info messages. In your template you can use;

{% if messages %}
<ul class="messages">
    {% for message in messages %}
    <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
    {% endfor %}
</ul>
{% endif %}

But this option will be available for your view layer not in model layer. Don't forget to checkout documentation.

berkeebal
  • 463
  • 4
  • 8
  • Thanks but But save method does not have request right? – Max Will Sep 02 '21 at 12:43
  • Yes like I said you can use messages framework in your view not in `save` method of your object. Because the goal in the messages framework is sending a text to your template and render it so you can send a message to user :) – berkeebal Sep 02 '21 at 14:17