Dynamic Django Forms: Hide or Show Fields with Alpine.js

Adi Ramadhan
2 min readOct 10, 2024

--

Reference https://www.djangoproject.com/ and https://alpinejs.dev/

Django hide/show form field

Step 1: Preparation, Create Django Project, Inital Migration
create virtualenv: virtualenv venv
start virtualenv: venv/Scripts/activate
install Django in virtualenv: pip install django==4.2
Create Django: django-admin startproject myproject
Go to myproject folder: cd myproject
Initial Migration: python manage.py migrate
Create app: python manage.py startapp myapp

Step 2: Project Setting: Register Apps, Set Templates Folder (myproject/settings.py)

...

INSTALLED_APPS = [
...
'myapp', #updated
]

...

TEMPLATES = [
...
'DIRS': [Path(BASE_DIR, 'templates')], #updated
...
]


...

Step 3: Create HTML Files in Templates Folder

Create templates folder in main app

Create templates/index.html with alpinejs

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My Project</title>
</head>
<body>
<h1>Coffee Form </h1>

<div x-data="{ selectedOption: '' }">
{{form.like_coffee.label}} {{ form.like_coffee }}
<div x-show="selectedOption === 'YES'">
{{form.coffee_choice.label}}: {{ form.coffee_choice }}
</div>
</div>

<script src="//unpkg.com/alpinejs" defer></script>
</body>
</html>

Step 4: Create forms myapp/forms.py

Create myapp/forms.py

from django import forms

LIKE_COFFEE_CHOICES = (
("NO", "NO"),
("YES", "YES"),
)

COFFEE_CHOICES = (
("", "---Choose--"),
("BLACK COFFEE", "BLACK COFFEE"),
("AMERICANO", "AMERICANO"),
("CAPPUCCINO", "CAPPUCCINO"),
("LATTE", "LATTE"),
("ESPRESSO", "ESPRESSO"),
)

class CoffeeForm(forms.Form):
like_coffee = forms.ChoiceField(label="Do you like coffee?", choices=LIKE_COFFEE_CHOICES, widget=forms.RadioSelect(attrs={'x-model': 'selectedOption'}))
coffee_choice = forms.ChoiceField(label="Choose the coffee you like most", required=False, choices=COFFEE_CHOICES)

Step 5: Create Function Views myapp/views.py

from django.shortcuts import render
from . import forms

# Create your views here.
def index(request):
form = forms.CoffeeForm
return render(request, 'index.html', {'form': form})

Step 6: Setup URLS

Create myapp/urls.py

from django.urls import path
from . import views

urlpatterns = [
path("", views.index, name="index"),
]

Update myproject/urls.py

from django.contrib import admin
from django.urls import path, include #updated

urlpatterns = [
path('admin/', admin.site.urls),
path('', include('myapp.urls')), #updated
]

Step 7: Run Server and Testing

Run Server: python manage.py runserver
Testing:

Open http://127.0.0.1:8000/

--

--

Adi Ramadhan
Adi Ramadhan

No responses yet