There will be 3 steps. You don't need to know anything about
HTMX - I'll show you the minimal to get
you doing. I've already created a Django project, as well as a Django
app called sim
.
The video follows the written guide below. Let's go 🐎
1. Add your views
- Add a view to render the template
- Add a view to handle the form and return html as a response
# views.py
from django.shortcuts import render
from django.http import HttpResponse
def sample_post(request, *args, **kwargs):
print(f'{request.POST = }')
name = request.POST.get('name', '')
email = request.POST.get('email', '')
favourite_colour = request.POST.get('favourite_color', '')
if name and email and favourite_colour:
return HttpResponse('<p class="success">Form submitted successfully! ✅</p>')
else:
return HttpResponse('<p class="error">Please provide both name and email and favourite color.❌</p>')
def example(request):
return render(request, 'example.html')
2. Add your url routes
- Create a
urls.py
file in your app if you don't have one already (for me, I createdsim/urls.py
- Add the below to
urls.py
from . import views
urlpatterns = [
path('example/', views.example, name='example'),
path('sample-post/', views.sample_post, name='sample-post'),
]
3. Add your html template, containing HTMX
- Create a
templates
folder in your app. - Add a file called
example.html
to yourtemplates
folder - Add the below code, containing your html form and HTMX, to
example.html
- View your html page and test submitting your form.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Simple form</title>
<script src="https://unpkg.com/htmx.org@1.9.4" integrity="sha384-zUfuhFKKZCbHTY6aRR46gxiqszMk5tcHjsVFxnUo8VMus4kHGVdIYVbOYYNlKmHV" crossorigin="anonymous"></script>
</head>
<body>
<h1>Please add your most valuable data for us to sell:</h1>
<form hx-post="{% url 'sample-post' %}" hx-target="#message">
{% csrf_token %}
<input type="text" name="name" placeholder="Name" required>
<input type="email" name="email" placeholder="Email" required>
<input type="color" name="favourite_color" placeholder="Favourite color" required>
<input type="submit" value="Submit">
</form>
<div id="message"></div>
</body>
</html>
Bonus: Validate your user input with a django form
- Create
forms.py
in your app folder (for mesim/forms.py
and add the below form code to it - Update your
views.py
to validate user data using your new django form.
# forms.py
from django import forms
class SampleForm(forms.Form):
email = forms.CharField()
name = forms.CharField(min_length=3)
favourite_color = forms.CharField()
# views.py
from django.shortcuts import render
from django.http import HttpResponse
from sim.forms import SampleForm
def sample_post(request, *args, **kwargs):
form = SampleForm(request.POST or None)
if form.is_valid():
# form.cleaned_data now contains the validated data
print(f'{ form.cleaned_data= }')
return HttpResponse('<p class="success">Form submitted successfully! ✅</p>')
else:
# form.errors contains the form validation errors
return HttpResponse(f'<p class="error">Your form submission was unsuccessful ❌. Please would you correct the errors? The current errors: {form.errors}</p>')
def example(request):
return render(request, 'example.html')
Finished (HTMX is great)
Congratulations! You can now submit data asynchronously in a simple and robust way using HMTX.
Compared to adding javascript on the frontend (such as with Alpine JS, or with Vue or React or Svelte), using HTMX means that your code is:
- Much easier to test (your can test almost everything using Django tests on the backend)
- In one place. Your code is not spread across multiple places, such as a frontend server and a backend server.
- Faster to build (because you get fewer bugs because of the above points)
Build your Django frontend even faster
I want to release high-quality products as soon as possible. Probably like you, I want to make my Django product ideas become reality as soon as possible.
That's why I built Photon Designer - an entirely visual editor for building Django frontend at the speed that light hits your eyes. Photon Designer outputs neat, clean Django templates, using HTMX.