2017-02-13 3 views
0

私はページをリフレッシュせずに私のpythonデータベースにデータを追加するajax関数を持っています(私はdjango Webフレームワークを使用しています)。私はデータを返し、ページのリフレッシュを避けるためにhtml appendを使ってこれをテンプレートに追加します。ajaxでdjangoリンクでhtmlを追加する

しかし、この新しく追加されたデータを、それが属する実際のレコードにリンクしたいと思います。したがって、ユーザーが '新しく追加された行'をクリックすると、レコードビューに移動して項目を追加できます。私がしたいと思う何

$(document).ready(function() { 

$('#timesheet-form').on('submit', function(event){ 
    event.preventDefault(); 
    console.log("add a timesheet"); 
    createtimesheet(); 
}); 

function createtimesheet() { 
    console.log("create timesheet is working!") 
    $.ajax({ 
     url : "{% url 'tande:createtimesheet' %}", 
     type: "POST", 
     data: { datestart : $('#start').val(), dateend : $('#end').val()}, 

     success : function(json) { 
      var html = '<tr><td>'+json.startdate+'</td><td>'+json.enddate+'</td><td>'+json.status+'</td><</tr></br><p>'+json.error+'</p></br>'; 
      console.log("success"); 
      $('#timesheet-list').append(html); 
     }, 

     error : function(xhr,errmsg,err) { 
      // what to do when there is an error 
      } 
     }); 
    }; 
}) 

はこのようなものである:これは私が問題を抱えているところ...私はエラーを取得せずにジャンゴリンクで投げることができないです... は、ここに私のAjaxです - それは恐ろしいですにもかかわらず:

var html = '<tr><td><a href='{% url "tande:timesheet" timesheet_id=sheet.id %}' class="class2">'+json.startdate+'</a class="class2"></td><td>'+json.enddate+'</td><td>'+json.status+'</td><</tr></br><p>'+json.error+'</p></br>'; 

しかし、私はで...

Djangoのリンクを置くことができないこれに対する回避策はありますか?

+2

javascript cantはdjangoと直接対話します。あなたはajaxを使ってdjangoがhtmlをjson形式で保存してからjavascriptで置き換えることができます。 – ExperimentsWithCode

+0

jsonresponseとして返すと、リンクを動作させるためにページをリフレッシュする必要はありませんか? –

答えて

0

@ExperimentsWithCodeで示唆されているように、私はjsonでhtmlの文字列を配信しなければなりませんでした。フィールドIDをビューに表示し、URLに次のように挿入する必要がありました。

def createtimesheet(request): 
    print "create timesheet view" 
    if request.method == "POST": 

     #Get all the data and do stuff 

     # now we can create the timesheet! 
     peach = TimeSheet(start_date=start_date_formatted, end_date=end_date_formatted, person_id=person) 
     peach.save() 

     #json response data for the link 
     response_data['linkstart'] = "<a href='/tande/"+str(peach.id)+"/person/timesheet/' class='class2'>" 
     response_data['linkend'] = "</a class='class2'>" 
     #other response data 

     return JsonResponse(response_data) 

私はビューにリンクを作成しました。次に、次のようにHTMLの追加を変更します。

var html = '<tr><td>'+json.linkstart+json.startdate+json.linkend+'</td><td>'+json.enddate+'</td><td>'+json.status+'</td><</tr></br><p>'+json.error+'</p></br>'; 
関連する問題