简体   繁体   English

将对象通过 Django 模板传递给 javascript

[英]Passing objects through Django template to javascript

I am making a website using Django and I want to pass a python object from my view (where it is created) through the Django template and to a Dajax call.我正在使用 Django 创建一个网站,我想通过 Django 模板从我的视图(创建它的位置)传递一个 python 对象并传递给 Dajax 调用。 The problem is that by the time it gets to dajax it has been turned into type unicode.问题是当它进入 dajax 时,它已经变成了 unicode 类型。

In my Template在我的模板中

<script>
var emailer = "{{emailer|safe}}"; <---If I omit the quotes here then I get a javascript error.
sessionStorage.setItem('emailer',emailer);
$(document).ready(function(){

  $('.send').on('click', function(e){  
    var emailer = sessionStorage.getItem('emailer');

    Dajaxice.InterfaceApp.sendEmail(submitverify,{'emailer':emailer});
  });
});

</script>

The dajax function dajax 函数

@dajaxice_register(method='GET')
def sendEmail(emailer):
    logger.warning("type: %s, %s" % (type(emailer),emailer))
    email_body = "message"
    emailer.addToMessage(email_body)
    emailer.send()

    message = "Email Sent"
return json.dumps({'message':message})

Here the logger statement returns: type: <type 'unicode'>, <Utils.SIMPL_Emailer instance at 0x103142ab8> .这里记录器语句返回: type: <type 'unicode'>, <Utils.SIMPL_Emailer instance at 0x103142ab8> Is there any way to fix this so that I get my emailer object instead of a unicode string?有什么办法可以解决这个问题,以便我得到我的电子邮件对象而不是 unicode 字符串?

First try to understand what is happening:首先尝试了解发生了什么:

On your template you're trying to save a Python object to a Javascript var:在您的模板上,您尝试将 Python 对象保存到 Javascript var:

var emailer = "{{emailer|safe}}";`

But it's not possible.但这是不可能的。 When your template is rendered by Django what you really get is a call to object __str__() method and your Javascript will store the <Utils.SIMPL_Emailer instance at 0x103142ab8> value on your emailer var.当您的模板由 Django 呈现时,您真正得到的是对对象 __str__() 方法的调用,并且您的 Javascript 会将<Utils.SIMPL_Emailer 实例存储在 0x103142ab8>值在您的电子邮件变量上。 And remember: this code run in the client browser.请记住:此代码在客户端浏览器中运行。 That's why you get an error when you remove the quotes.这就是为什么在删除引号时会出现错误的原因。

To solve it you need to first serialize your emailer object (Turn it into something that could be represented as a String, for example, and then turned back to Python Object).要解决它,您需要首先序列化您的电子邮件对象(例如,将其转换为可以表示为字符串的内容,然后再转换回 Python 对象)。 But as pointed by Peter DeGlopper it is a very insecure approach.但正如 Peter DeGlopper 所指出的那样,这是一种非常不安全的方法。 Never, ever deserialize an whole object that was public accessible.永远不要反序列化一个可以公开访问的整个对象。 Instead send only the email data to your template.而是仅将电子邮件数据发送到您的模板。 You can create a dictionary with this data, turn it into JSON (it's a serialization too, but this time you are serializating only data) and then pass it to your template.您可以使用这些数据创建一个字典,将其转换为 JSON(这也是一个序列化,但这次您仅序列化数据),然后将其传递给您的模板。

So do not put your emailer on the template context.所以不要把你的电子邮件放在模板上下文中。 Instead create a dictonary and pass it to the template.而是创建一个字典并将其传递给模板。

Then in your Python sendEmail(emailer) method you'll need to instanciate a new Emailer object and feed it with the data, like:然后在您的 Python sendEmail(emailer) 方法中,您需要实例化一个新的 Emailer 对象并为其提供数据,例如:

@dajaxice_register(method='GET')
def sendEmail(email_json):
    email = json.loads(email_json) # email_json is a json with your email data only
    logger.warning("type: %s, %s" % (type(email_json),email_json))
    emailer = Emailer("<with all your params...>")
    emailer.addToMessage(email.get('body'))
    emailer.send()

    message = "Email Sent"
    return json.dumps({'message':message})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM