Search code examples
djangoformssubmitinternal-server-error

form throwing a internal server error on submit with ajax, django


I have a form that is throwing a internal server error when i submit it with data

it says it is due to an integrity error:

IntegrityError at /cookbook/createrecipe/

(1048, "Column 'original_cookbook_id' cannot be null")

what is weird is that i dont have a column original_cookbook_id - what i do have is an original_cookbook that is a foreign key to a cookbook model

here is the view that is giving the error:

def createrecipe(request):
        print "entering createrecipeview"
        if request.method == 'POST':
            print "form is a post"
            form = RecipeForm(request.POST)
            print form.errors
            if form.is_valid():
                print "form is valid"
                form = RecipeForm(initial = {'original_cookbook' : request.user.cookbooks.all()[0]})// this is where the error is being thrown
                form.save()

                t = loader.get_template('cookbook/create_form.html')
                c = RequestContext(request, {
                'form': form,
                })

                data = {
                'replace': True,
                'form': t.render(c),
                'success': True,
                }

                json = simplejson.dumps(data)
                return HttpResponse(json, mimetype='text/plain')
            else:
                print "form is invalid"
                form = RecipeForm(request.POST)
                t = loader.get_template('cookbook/create_form.html')
                c = RequestContext(request, {
                    'form':form,
                })

                data ={
                    'form': t.render(c),
                    'success': False,
                }

                json = simplejson.dumps(data)
                return HttpResponse(json, mimetype='text/plain')

i think i might be declaring the original_cookbook the wrong way

anyone else have any experience with _id being appended to a foreign key/ have any idea how i might be able to resolve this issue

thanks a lot

katie

update

here is my javascript function

<script type="text/javascript"> 

$(document).ready(function(){

    function hijack() {
        var form = $('form#createrecipeform');
        form.each (function(){
            this.reset();
            });
        form.submit(function(e) {
            e.preventDefault();
            console.log('ajax form submission function called successfully.');
            //form = $(this);
            console.log(form)
            var serialized_form = form.serialize();
            $.ajax({ type: "POST", 
                url: $(this).attr('action'),
                data: serialized_form, 
                success: (function(data) { 
                    console.log('ajax success function called successfully.');
                    data = $.parseJSON(data);
                    if (data.success) {
                        console.log('success');
                        //right now it is logging success to 
                        //console but nothing else is happening
                        //what else should happen on data success?
                    } else {        
                        console.log('failure');
                        var newForm = data.form;
                        form.replaceWith(newForm);
                        hijack();
                    }
                })
            });
            return false;
        });
    };

    hijack();

});
</script> 

Solution

  • You do have an original_cookbook_id field. That's where the pk for the foreign key is store in the table. Django automagically appends the _id bit. All the error means is that that field is set to NOT NULL, and you didn't provide a value to original_cookbook to fill it in with.

    UPDATE

    There's nothing "wrong" per se, but a few things to note. First, initial only sets the initial value that appears in the form (obviously enough). However, if it's later set back to empty by the user or some other action, it's still empty, i.e. initial has no true effect on the eventual posted data.

    You didn't post your javascript, so I can't speak to how you're submitting the form, but that too could potentially be an issue. If you're not submitting the field with the rest of the AJAX post, for whatever reason, it doesn't matter what the actual field may or may not be set to.