开发者

When does a submitted django form actually save to the database?

I ask this question because I've implemented a javascript solution to nested inlines (it feels a bit hack like, but also seemed the easiest and quickest solution at the time...) which has given me some unexpected results.

jQuery adds extra input sections to the admin form, which the normal form submit will just ignore (obviously) so I used jQuery forms plugin like so

function ajaxSubmit(form) {
  $(form).ajaxSubmit({
    success: function() {
      var item_data = $('.item-fields').fieldSerialize();
      var post_url = '/admin/menu_generator/' + context + '/' + menu_id + 'items/new/';
      $.post(post_url, item_data);
    };
  });
};

ajaxSubmit() and $(selector).ajaxSubmit are different, badly named, my apologies.

Either way, that bit of code submits the form normally, and on success does the second POST request which handles the inputs that jQuery added. This, I thought, would prevent the problem when the jQuery inputs require stuff in the database that hadn't been created yet. For clarity, an example:

A user can create sections, and each section can have many items. If the user creates a new section and adds new items, without doing a normal form submit first that section won't be in the database so the items can't be created either!

Unfortunately, my solution does not work. Even after the ajaxSubmit the new sections are not actually recorded in the database until after completion of all the js code - this surprised me and perhaps someone could enlighten me why? It might just be that the form plugin isn't suitable for this task.

EDIT :: There w开发者_如何学Cas a syntax error in my code, which is why it wasn't working... As you can see in the snippet above, there is a semi-colon at the end of the success function, which was breaking stuff.


Your form should include the path to the view (for none-ajax posts):

<form action="/test" method="post" accept-charset="utf-8" id="testform">

jquery-code:

$('document').ready(function(){
$("#testform").submit(function(){
    $.ajax({
        type: "POST",
        url: "/test",
        data: $(this).serialize(),
        success: function(data) {
             .....
    });
    $('#testform')[0].reset();
    return false;
}) ...

your view:

def test(request):
if request.is_ajax():
    name = request.POST.get('message', False)
    m = Message(message=name,user_id=request.user)
    m.save()
else: ...
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜