[英]Edit form field in Django on click and update in database
这就是我想要的。 我有一个UpdateView,它使用从数据库加载的字段从CreateView呈现表单。 相反,我的编辑表单具有只读的 html属性。 所以我需要的是在表单字段上单击以删除只读,当我输入新值时,当光标移到下一个字段时它将自动更新。
如何在没有提交按钮的情况下处理POST操作?
您可以使用JavaScript(Jquery)来做到, blur
事件
编辑:关于CSRF验证,请参阅https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax
有关$.post
请参见: https : //api.jquery.com/jQuery.post/
template.html
<script type="text/javascript" src="/media/js/jquery-1.10.2.min.js"></script>
<script>
// using jQuery
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
$(document).ready(function(){
$("#myinput").blur(function(){
var csrftoken = getCookie('csrftoken');
$.ajaxSetup({
beforeSend: function(xhr) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
});
$.post('/link-to-fun/',{"value":value});
});
});
</script>
<input type="text" id="myinput">
url.py
编写一个特殊的url(/ link-to-fun /)以在views.py中起作用
url(r'^link-to-fun$', views.change_db_value),
views.py
def change_db_value(request):
value = request.POST.get('value','')
# database operation
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.