Here's a detailed guide on how to send information from a Django HTML view to an
external API upon button submission:
1. Project Setup:
● Ensure you have a Django project and app set up with the necessary
dependencies (requests library for making HTTP requests).
2. HTML Form Creation (forms.py):
● Create a form in your app's forms.py file to handle user input. This form will
define the fields (username, password, etc.) the user will enter.
Python
from django import forms
class LoginForm(forms.Form):
username = forms.CharField(max_length=100, required=True)
password = forms.CharField(widget=forms.PasswordInput,
required=True)
3. HTML Template (templates/your_app/login.html):
● Create a template file (e.g., login.html) in your app's template directory
(templates/your_app/). This template will contain the HTML form and logic
to submit data to the view.
HTML
<!DOCTYPE html>
<html>
<head>
<title>Login Form</title>
</head>
<body>
<h1>Login</h1>
<form action="{% url 'your_app:login' %}" method="post">
{% csrf_token %} {{ form.as_p }}
<button type="submit">Login</button>
</form>
</body>
</html>
● Explanation:
○ The action attribute of the form element points to the URL pattern
(defined later) that will handle form submission.
○ The method attribute specifies the HTTP method (POST) to use for
sending data.
○ {% csrf_token %} includes a CSRF token for security to prevent
cross-site request forgery attacks.
○ {{ form.as_p }} renders the form fields dynamically from the
LoginForm class.
4. URL Pattern (urls.py):
● In your app's urls.py file, define a URL pattern to map the form submission
route to a view function.
Python
from django.urls import path
from . import views # Import views.py from your app
urlpatterns = [
path('login/', views.login_view, name='login'), # URL pattern for
login
# ... other URL patterns
5. Django View Function (views.py):
● Create a view function in your app's views.py file to handle form submission,
data processing, and sending the request to the external API.
Python
from django.shortcuts import render, redirect
from .forms import LoginForm # Import LoginForm from forms.py
import requests # Import requests library
def login_view(request):
if request.method == 'POST':
form = LoginForm(request.POST) # Create form object with
submitted data
if form.is_valid():
# Form data is valid, proceed with API call
username = form.cleaned_data['username']
password = form.cleaned_data['password']
# API call logic (replace with your actual API details)
api_url = 'https://your-external-api.com/login' # Replace
with your API URL
data = {'username': username, 'password': password} #
Replace with API data format
headers = {'Content-Type': 'application/json'} # Adjust
headers if needed
response = requests.post(api_url, json=data,
headers=headers)
if response.status_code == 200: # Successful login (adjust
based on API response)
# Handle successful login (e.g., redirect to home page,
set session data)
return redirect('home') # Replace with your desired
redirect URL
else:
# Handle login failure (display error message)
form.add_error(None, 'Login failed. Please check your
credentials.')
else:
form = LoginForm() # Create empty form for GET requests
return render(request, 'your_app/login.html', {'form': form})
● Explanation:
○ The login_view function handles GET and POST requests.
○ For POST requests, it creates a LoginForm object with the submitted
data (request.POST).
○ If the form is valid, it extracts the username and password from the
cleaned data.
○ Replace the placeholder API details
There are two main approaches to add a preloader to your Django HTML view for
the API call:
1. Using JavaScript:
This method involves using JavaScript to display a preloader while the API request is
being made and hide it once the response is received.
Here's a breakdown of the steps:
a) HTML Template (templates/your_app/login.html):
● Add a container element (e.g., a div) with a hidden class (e.g., hidden) to
hold the preloader content.
HTML
<!DOCTYPE html>
<html>
<head>
<title>Login Form</title>
</head>
<body>
<h1>Login</h1>
<div id="preloader" class="hidden">
<img src="{% static 'images/loading.gif' %}" alt="Loading..."
/>
</div>
<form action="{% url 'your_app:login' %}" method="post">
{% csrf_token %} {{ form.as_p }}
<button type="submit" id="submit-button">Login</button>
</form>
</body>
</html>
b) JavaScript Code (Optional - External File):
● Write JavaScript code to:
○ Show the preloader element (#preloader) when the submit button is
clicked.
○ Hide the preloader element once the response from the API is received
in the view function (use AJAX or fetch API).
○ You can handle potential errors and display appropriate messages.
JavaScript
// Assuming you have a function to handle the API call in your view
function submitLoginForm() {
// Show preloader
document.getElementById("preloader").classList.remove("hidden");
// Make API call using AJAX or fetch API
// ... (Your code to send the login data and handle response)
// Hide preloader on successful response or error
document.getElementById("preloader").classList.add("hidden");
}
// Attach event listener to submit button
document.getElementById("submit-button").addEventListener("click",
submitLoginForm);
c) Django View Function (views.py):
● No changes are required specifically for the preloader in the view function.
However, the JavaScript code might need to handle the response from the
API call (success or error) to control the preloader visibility.
2. Using Django Template Tags (Less Customization):
● This approach utilizes a custom template tag to display the preloader while
the view function processes the form submission. However, it offers less
flexibility compared to pure JavaScript.
a) Create a Custom Template Tag (templatetags/your_app/tags.py):
● Python
from django import template
register = template.Library()
@register.simple_tag
def show_preloader(is_processing):
"""
Simple template tag to conditionally show/hide preloader based on a
boolean value.
"""
return 'hidden' if not is_processing else ''
●
● b) Modify HTML Template (templates/your_app/login.html):
● HTML
<!DOCTYPE html>
<html>
<head>
<title>Login Form</title>
</head>
<body>
<h1>Login</h1>
<div id="preloader" class="{{ show_preloader request.processing
}}">
<img src="{% static 'images/loading.gif' %}" alt="Loading..."
/>
</div>
<form action="{% url 'your_app:login' %}" method="post">
{% csrf_token %} {{ form.as_p }}
<button type="submit">Login</button>
</form>
</body>
</html>
●
● c) Django View Function (views.py):
○ Add a boolean flag (request.processing) to indicate if the API call is
in progress. Set it to True before making the API call and False after
receiving the response.
● Python
# ... other code in login_view
if request.method == 'POST':
form = LoginForm(request.POST) # ... (existing code)
if form.is_valid():
# Set processing flag to True
request.processing = True
●
●