13

I'm trying to write a CRUD application using Djangos class based generic views. Following is the code i wrote to create a new user in the db.

  from django.views.generic import CreateView
  from django.contrib.auth.decorators import login_required
  from django.contrib import messages

  class UserCreateView(CreateView):
  """ 
  Display and accept a new user to be created in db
  """
    form_class = ProfileForm
    template_name = 'userdb/profile_form.html'
    success_url = '/organization/users/'

    def post(self, request, *args, **kwargs):
      messages.success(request, "Success", extra_tags='msg')
      return super(UserCreateView, self).post(request, *args, **kwargs)

    @method_decorator(login_required)
    def dispatch(self, *args, **kwargs):
      return super(UserCreateView, self).dispatch(*args, **kwargs)

Note that to add a success message to be displayed to the user I've had to extend the post function. I know this is not a good way to do this as, when this function gets called it's not decided whether the submitted form contains valid data. So my question is, Is there recommended way of combining Djangos messaging framework with class based generic views?

vim
  • 1,098
  • 9
  • 21

1 Answers1

16

The answer depends on what specifically you're looking to do with the messaging framework. If it needs to be called for every get request you'd naturally need to put it in the get method (point being there's no one right place to put this code).

Anyways, it sounds like you're looking for a place that's only triggered when the form is valid.

CreateView uses the ModelFormMixin which implements a form_valid method which is only fired upon successful form saving. Perfect!

def form_valid(self, form):
    messages.success(self.request, "Success", extra_tags='msg')
    return super(UserCreateView, self).form_valid(form)  
    # ModelFormMixin will now save
    # FormMixin will now redirect to success_url()
    # override above behavior if you need to do something with the object
Yuji 'Tomita' Tomita
  • 115,817
  • 29
  • 282
  • 245
  • I tried implementing 'form_valid' function before but it didn't work as I couldn't find a way to access the request object. This works fine Thank you very much! – vim Jun 21 '11 at 06:32