views:

49

answers:

1

I have an edit page for my object. Because I've divided data in two tabs, I'm using jquery-ui. On the first tab (#core_data) I'm loading object's main data. Form is submited via Ajax :

<form method="post" class="object_form" id="event-core-form" action="{% url edit_event_data event.id %}" enctype="multipart/form-data">
    {{ form.as_p }}
    <p>
        <input class="object-submit" id="event-data-save" type="submit" value="Save data">
    </p>
</form>

js:

$("#event-data-save").livequery("click", function() {
    $("#event-core-form").ajaxSubmit({
        "success": function(data) {
            data = JSON.parse(data)
            $("#core-data").html(data["form"]);               
        }
    });
    return false;
})

and a function is run, and my debug says that it is instantly called 2 times :

def edit_event_data(request, event_id,):
    template_name="management/core_event.html" 
    event = get_object_or_404(Event, pk=event_id)
    form = EventForm(instance=event, data=request.POST)

    if form.is_valid():
        form.save()
        form = EventForm(instance=event)

    form_html = render_to_string(template_name, RequestContext(request, {
        "event" : event,
        "form" : form,
    }))

    result = simplejson.dumps({
        "form": form_html,
        "message": "Data saved."
    }, cls=LazyEncoder)

    return HttpResponse(result, mimetype='application/javascript')

What more, after successfully submitting hitting save once again gives me a raw form rendered :/ Here's the form I'm using. I think that this may be the reason for my problems:

class EventForm(forms.ModelForm):   
    def __init__(self, *args, **kwargs):
        logging.debug("form - init")
        super(EventForm, self).__init__(*args, **kwargs)

    (...)

    def save(self, *args, **kwargs):   
        (...)

        logging.debug("form - save")
        post = super(EventForm, self).save(*args, **kwargs)
        post.save()

Since in my debug I can see I think too many __init__'s

2010-10-28 23:35:08,210 DEBUG form - init
2010-10-28 23:35:34,065 DEBUG form - init
2010-10-28 23:35:34,068 DEBUG form - save
2010-10-28 23:35:34,073 DEBUG form - init
2010-10-28 23:35:34,258 DEBUG form - init
2010-10-28 23:35:34,262 DEBUG form - save
2010-10-28 23:35:34,270 DEBUG form - init

Can anyone help ?


EDIT:

After removing jquery-ui still the same. Removing livequery also gives no results.

+1  A: 

Why are you instantiating a new form after you save the original one?

if form.is_valid():
    form.save()
    # what's the point of the next line?
    form = EventForm(instance=event)

This is almost certainly the cause of your duplicated __init__ call. Why are you doing it? You already have a form.

Also, you've forgotten to stop the click action from completing within your JS.

$("#event-data-save").livequery("click", function(e) {
    e.preventDefault();
    ...
})
Daniel Roseman