Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem with class based generic views in Django

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?

like image 640
vim Avatar asked Jun 21 '11 04:06

vim


1 Answers

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
like image 175
Yuji 'Tomita' Tomita Avatar answered Oct 23 '22 22:10

Yuji 'Tomita' Tomita