2017-02-18 37 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吗?我会告诉你我的问题 –

相关问题