简体   繁体   中英

Edit form field in Django on click and update in database

Here's what I am looking for. I have an UpdateView, which renders the form from CreateView with fields loaded from database. Instead my edit form has readonly html attribue. So what I need is to drop readonly on click on the form field and when i enter new value it will be automaticaly updated when cursos moves to the next field.

How do i handle POST actions with out submit button?

you can use JavaScript(Jquery) to do so, blur event

EDITED: about CSRF verification,see https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax

about $.post see: 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

write a special url(/link-to-fun/) to function in 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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