2017-02-18 80 views
0

我需要將舊值更改爲模板文件中的新值。如何用模板中的新值用python替換舊值?

其實,當用戶輸入10位數的手機號碼時,python函數會調用。如果我在日誌中檢查它顯示值,但在HTML文件中它沒有顯示值。如何在views.py中調用函數第二次獲取該值?

views.py

from django.views.decorators.csrf import csrf_exempt 
import json 
@csrf_exempt 
def default(request): 
    if request.is_ajax(): 
     print("inside the ajax") 
     phone_no = request.POST.get('phone_no') 
     print(phone_no) 
     dict = {'phone_no': phone_no} 
     template_name = 'mobile_recharge.html' 
     extended_template = 'base.html' 
     dummy_var = 'test' 
     print(dummy_var) 
     if request.user.is_authenticated(): 
      extended_template = 'base_login.html' 
     return render(request,template_name, {'extended_template': extended_template,'phone_no': phone_no,'dummy_var': dummy_var}) 
template_name = 'mobile_recharge.html' 
extended_template = 'base.html' 
dummy_var = 'test' 
if request.user.is_authenticated(): 
    extended_template = 'base_login.html' 
return render(
    request, template_name, 
    {'extended_template': extended_template,'dummy_var': dummy_var} 
) 

腳本

<script type="text/javascript"> 
$(document).ready(function() { 
    $('#phone_number').on('input', function() { 
     if ($(this).val().length >= 10) { 
      alert("user enter 10 digits numbers"); 
      var phone_no = $('#phone_number').val() 
      console.log(phone_no); 
      $.ajax({ 
       type: "POST", 
       url: "http://localhost:8090/", 
       data: {'phone_no' : phone_no}, 
       dataType: "json", 
       success: function(msg) 
       { 
        //alert(msg.phone_no); 
       } 
      }); 
      return; 
     } 
    }); 
    }); 
</script> 

HTML

{{phone_no}} {{ dict }} {{dummy_var}} 

如果我在模板中調用上述變量。我沒有得到任何結果。如何獲得結果?

+0

能否請你再次閱讀你的問題並糾正它? –

+0

根據我所瞭解的您要做的事情,我會說,重新加載頁面或使用javascript更新phone_no。目前無處可更新它。 –

+0

我想將dummy_var結果傳遞給html文件。怎麼做? –

回答

0

試試這個:

from django.views.decorators.csrf import csrf_exempt 
from django.http import HttpResponseForbidden 
import json 
@csrf_exempt 
def default(request): 
    if request.is_ajax() and request.user.is_authenticated() and 'phone_no' in request.POST: 
     phone_no = request.POST['phone_no'] 
     dummy_var = 'test' 
     dict = {'phone_no': phone_no} 

     context = {'phone_no': phone_no, 'dict': dict, 'dummy_var ': dummy_var} 
     return render(request, 'mobile_recharge.html', context) 
    else: 
     HttpResponseForbidden() 

如果你真的需要打印變量,使用記錄來代替。

+0

我仍然沒有在html文件中獲得任何價值。當用戶輸入10位數的手機號時,不是第一次ajax函數會調用python函數。 python函數不會將結果發送到html文件。當我打印值它顯示日誌文件中的值 –

0

您可以看到如何將變量添加到其official tutorial中的django模板上下文中。您可以輕鬆地使用Django Debug Toolbar來調試此上下文。

您可能想使用login_required decorator並依靠django身份驗證系統設置登錄模板。另一個建議:不要使用print進行調試,您可以使用logging modulesnippet進行快速查找。

注意:你的問題有一個令人困惑的代碼,我想你粘貼一些地區的兩倍

+0

我的代碼不是兩次。我需要的是如何發送python變量值到html文件? –

+0

縮進是錯誤的呢?你檢查了我給你的所有文檔嗎?已經測試了Django Debug Toolbar? – chachan

+0

你有Skype的ID嗎?我會告訴你我的問題 –