1

I'd like to save user input in a text area automatically without any submit button. The UI I'm looking for is google docs kind of thing. Ideally there should be a time interval of 2-3 seconds after the input to prevent submitting requests every-time something is typed.

Here's my current implementation.

model:

class ActionField(models.Model):
content = models.TextField()

def __str__(self):
    return self.content

view:

def action_view(request):
all_todo_items = ActionField.objects.all()
return render(request, 'action.html',
              {'all_items': all_todo_items})

and html displaying the form and the submit button I'd like to remove:

<form action="/add/" method='post'>{% csrf_token %}
    <textarea name="content" rows="30" cols="100"></textarea>
    <br><br>
 <input type="submit" value="enter">
</form>

After some quick research, it seems this would be normally done with AJAX or Jquery but is there any simple approach using purely Django? I'm new to the framework as well as html / FE.

inferense
  • 57
  • 1
  • 6

1 Answers1

2

I've never heard about that possibility. Django (just like any other backend framework) can only send or receive data to or from your browser. It can't somehow make your browser send something without any script at the browser's side. However, there is a script that you can use:

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
  <form action="/add/" method='post'>{% csrf_token %}
    <textarea name="content" rows="30" cols="100"></textarea>
    <br><br>
     <input type="submit" value="enter">
  </form>
    
  <script>
    $("textarea[name='content']").on("change", function() {
      $.ajax({
        url: '/add/', // or better {% url 'view-name-in-urls.py' %}
        method: 'POST',
        data: {
          content: $(this).val(),
          csrfmiddlewaretoken: '{{ csrf_token }}'
        }
      }).done(function(msg) {
        alert("Data saved");
      })
    });
  </script>
</body>

I know that the ability to do everything on the server-side is very convenient and looks nice but it's just impossible. You need to learn how to deal with the server on the client-side too.

You can read more about forms here https://docs.djangoproject.com/en/3.1/topics/forms/

and ajax https://api.jquery.com/jquery.ajax/

szjakub
  • 66
  • 4
  • Thanks, that makes sense. Your implementation works and submits the request after a click, I assume I'll just alter the JS function and add an event listener to save after an input is typed? – inferense Oct 15 '20 at 16:21
  • Sure, it can be done in any js framework or just in pure JS. I just found a related question https://stackoverflow.com/questions/6396101/pure-javascript-send-post-data-without-a-form so you can choose the method you like. Here is my code that I tested my solution with https://codeshare.io/amB7NX it expires in 24 hours – szjakub Oct 15 '20 at 20:20