How to Use fetch in django template
50
Introduction
The Fetch API is a modern JavaScript interface for making HTTP requests to servers, which simplifies the process of fetching resources asynchronously. In a Django application, you can use the Fetch API to make AJAX requests, enabling dynamic content updates without needing to reload the entire page. This is particularly useful for creating interactive and responsive web applications.
Prerequisites
Before we embark on our AJAX journey, ensure you have the following:
- Django Project: A Django project set up and running.
- Basic Knowledge of Django and JavaScript:
For this tutorial, we will send a post request to our server by submitting a form
1. views.py
# views.py
from django.http import JsonResponse
from django.shortcuts import render
def my_view(request):
if request.method == "POST":
data = request.POST.get('data', '')
response_data = {'message': f"You sent: {data}"}
return JsonResponse(response_data)
return render(request, 'my_template.html')
2. Configure URLs
# urls.py
from django.urls import path
from . import views
urlpatterns = [
path('fetch/', views.my_view, name='my_view'),
]
3. Designing our template
<!-- templates/my_template.html -->
<!DOCTYPE html>
<html>
<head>
<title>Fetch in Django</title>
</head>
<body>
<h1>FETCH in Django</h1>
<form id="myForm">
<input type="text" name="first_name" placeholder="Enter first name">
<input type="hidden" name="csrfmiddlewaretoken" id="csrfmiddlewaretoken" value="{{ csrf_token }}">
<button type="button" onclick="submitForm()">Submit</button>
</form>
<div id="result"></div>
<script>
function submitForm() {
varcsrfmiddlewaretoken = document.querySelector("#csrfmiddlewaretoken").value
var datatoSubmit = document.querySelector('input[name="first_name"]').value;
fetch('/fetch/', {// Replace with your view URL pattern
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRFToken': varcsrfmiddlewaretoken
},
body: JSON.stringify({ "data":datatoSubmit })
})
.then(response => response.json())
.then(data => {
document.getElementById('response-message').textContent = data.message;
})
.catch(error => console.error('Error:', error));
}
</script>
</body>
</html>
When the button is clicked, it triggers the submitForm function which submits the form to our backend which can be processed further.
Django uses CSRF tokens to protect against Cross-Site Request Forgery attacks, which occur when a malicious website tricks a user into submitting a form or making a request to your Django application, that is why we added the X-CSRFToken header when sending the request.
With this, you can perform other actions like GET, DELETE, PATCH, PUT etc.
Conclusion
Integrating the Fetch API with Django allows you to make asynchronous HTTP requests to your server, providing a smoother and more dynamic user experience. By following the steps outlined above, you can set up a Django view to handle requests, configure URLs, and create a client-side script to send and receive data using fetch.