# Generic views for newforms library

def nf_update_object(request, model, object_id=None, fields=[], template_name=None, extra_context={}, post_save_redirect="../", context_instance=None, my_callback=None):
    
    object = get_object_or_404(model, pk=object_id)
    ObjectForm = newforms.form_for_instance(object, fields=fields, formfield_callback=my_callback )

    if request.POST:
        form = ObjectForm(request.POST)
        if form.is_valid():
            object_updated = form.save()
            log.change_object(object_updated, request.user.username)
            return HttpResponseRedirect(post_save_redirect)
    else:
        form = ObjectForm()
    
    context = {'form':form, 'object':object, 'add':False}
    context.update(extra_context)

    if not template_name:
        template_name = "%s/%s_form.html" % (model._meta.app_label, model._meta.object_name.lower())

    if context_instance:
        return render_to_response(template_name, context, context_instance=context_instance)
    else:
        return render_to_response(template_name, context, context_instance=RequestContext(request))

def nf_create_object(request, model, fields=[], template_name=None, extra_context={}, post_save_redirect="../", context_instance=None, my_callback=None):
    
    ObjectForm = newforms.form_for_model(model, fields=fields, formfield_callback=my_callback )

    if request.POST:
        form = ObjectForm(request.POST)
        if form.is_valid():
            object_created = form.save()
            log.add_object(object_created, request.user.username)
            return HttpResponseRedirect(post_save_redirect)
    else:
        form = ObjectForm()
    
    context = {'form':form, 'object':object, 'add':True}
    context.update(extra_context)
    if not template_name:
        template_name = "%s/%s_form.html" % (model._meta.app_label, model._meta.object_name.lower())

    if context_instance:
        return render_to_response(template_name, context, context_instance=context_instance)
    else:
        return render_to_response(template_name, context, context_instance=RequestContext(request))