I’m building a form with Django and trying to get the following behaviour:
Among 4 possible answers on question genre
, if the user chooses the answer AUTRE
, display question genre_preciser
and make the answer mandatory. Otherwise, do not display genre_preciser
.
I’d like to use something similar to htmx, as my proficiency in Javascript is close to 0.
I’ve been asking the question to the htmx community and understand that on htmx side, I would have to deal with hx-get
. However I’m rather lost from here: what URL do I have to pass? The whole form is on a single page, I don’t have any separate URL.
How would you do? Is there an easier way to do this?
Thanks in advance!
models.py
class Questionnaire(models.Model):
class Genre(models.TextChoices):
FEMININ = 'Féminin', _('Féminin')
MASCULIN = 'Masculin', _('Masculin')
AUTRE = 'Autre', _('Autre (préciser)')
genre = models.CharField(
choices=Genre.choices,
null=True,
blank=False
)
genre_preciser = models.TextField(
null=True,
blank=True
)
forms.py
class QuestionnaireForm(forms.ModelForm):
class Meta:
model = Questionnaire
fields = ['genre', 'genre_preciser']
views.py
class CreerSoumission(CreateView):
model = Questionnaire
form_class = QuestionnaireForm
template_name = 'template.html'
urls.py
urlpatterns = [
path('', views.CreerSoumission.as_view(), name='soumettre'),
]
template.html
<form action="" method="post">
{% csrf_token %}
<table>
{{ form.as_table }}
</table>
<input type="submit" value="Submit">
</form>