在Django中动态设置默认表单值 [英] Dynamically set default form values in django

查看:122
本文介绍了在Django中动态设置默认表单值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试找到一种动态设置默认表单值的方法.因此,例如,如果我在网页上添加了Facebook登录功能,并且可以从Facebook JavaScript返回的信息中获取他的名字和姓氏,那么我希望能够将这些值设置为给定的形式. (基本上,这样我就可以将用户放入数据库中了) 我希望有某种

I'm trying to find a way to dynamically set default form values. So for example, if I add a facebook login feature on my webpage, and I can get his first name and last name from what the facebook javascript returns, I want to be able to set these values as the new "value" parameter in the given form. (basically so I'm able to put the user in my database) I was hoping that there is some sort of

{{ form.firstname.default = Javascript.return.firstname }}

我可以插入模板的

但没有... 有任何想法吗?谢谢.

that I can insert into a template but there isn't... Any ideas? Thank you.

编辑;;也许最好先将信息传递到views.py中?但是我该怎么办呢?我只是考虑在javascript字段中手写输入内容,这很烦人...

Edit;; Maybe it would be better to first pass in the information into a views.py? But how would I do this? I am just considering hand writing the inputs out in the javascript field, which would be annoying...

推荐答案

Django生成的代码都是服务器端的代码,它的模板不能使用加载页面时不可用的任何内容.您需要使用javascript设置值.

The code generated by Django is all server-side, its templates can't use anything which isn't available when the page is loaded. You need to use javascript to set the value.

例如,如果您的表单如下所示:

For example, if your form looks like this:

<form id="login">
 <input name="firstname" />
</form>

您可以使用此javascript(假设您使用的是jQuery):

You could use this javascript (assuming you're using jQuery):

// Do the facebook login, set the var fname to the first name, then:
$('#login [name=firstname]').val(fname);

这篇关于在Django中动态设置默认表单值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆