Question

I have a mixin for a custom FormView class that simply adds a success message if the save was successful, so:

class MessagesMixin(object):

    def form_valid(self, form):
        response = super(MessagesMixin, self).form_valid(form)
        messages.add_message(self.request,
                             messages.SUCCESS,
                             'Successfully created %s' % form.instance)
        return response

As you can see, this only really covers creation. If the instance is updated the message will still say "created". Is there a way to distinguish between creation/updating in the form_valid method?

Was it helpful?

Solution

One solution would be to add a property to your mixin and then set it in your Update and Create views. You can define a static property or overload the get_form_valid_msg if you need something dynamic. Untested code:

from django.core.exceptions import ImproperlyConfigured

class MessagesMixin(object): 
    @property
    def form_valid_msg(self):
        raise ImproperlyConfigured("you're missing the 'form_valid_msg' property")

    def get_form_valid_msg(self):
        return self.form_valid_msg

    def form_valid(self, form):
        response = super(MessagesMixin, self).form_valid(form)

        msg = 'Successfully {form_valid_msg} {form}'.format(
            form_valid_msg=self.get_form_valid_msg(),
            form=form.instance
        )

        messages.success(self.request, msg)

        return response
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top