Search code examples
djangodjango-modelsdjango-rest-frameworkdjango-templatesdjango-messages

Django Messaging Framework in the save() function


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)

Solution

  • 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.