def process_form(request, FormClass, *args, **kwargs): """Form processing helpers allowing to keep DRY in views. Arguments: - ``request``: HttpRequest instance - ``FormClass``: form to process - ``dest_url``: destination url to redirect after successful form saving. If it is not present, then the method ``get_absolute_url`` of object returned by form will be used. In case of its unavailability user will be redirected to current page. - ``on_success``: function to run if form was successfully saved, should receive 1 argument. ``dest_url`` and ``on_success`` should always be keyword arguments. All other arguments are passed directly to FormClass' init. (c) Alexander Solovyov under terms of new BSD License """ if not FormClass: return None dest_url = kwargs.pop('dest_url', None) on_success = kwargs.pop('on_success', None) no_redirect = kwargs.pop('no_redirect', None) if request.method == 'POST': form = FormClass(data=request.POST, files=request.FILES, *args, **kwargs) if form.is_valid(): obj = form.save() if not dest_url and hasattr(obj, 'get_absolute_url'): dest_url = obj.get_absolute_url() if on_success: on_success(obj) if not no_redirect: raise RedirectException(dest_url or '.') else: form = FormClass(*args, **kwargs) return form