6

I’m trying to add a conditional field to a wagtail page type model, the conditional fields may look like as shown in the below image. There are two fields, Question and Answer. The Answer field values should be displayed with respect to the selection of the Question field

enter image description here

If we select Toyota from Question then Camry and Land Cruiser should be displayed in the Answer drop down, if we select Honda then Civic and Accord should be displayed in the Answer.

In blocks.py I have two classes which are responsible for Questions and Answers fields respectively

class ConditionsQuestionBlock(blocks.ChooserBlock):
  widget = Select
  class Meta:
    icon = "question"

  @cached_property
  def target_model(self):
    return Question

  @cached_property
  def field(self):
    return forms.ModelChoiceField(
        queryset=Question.objects.all(),
        widget=self.widget,
        required=self._required,
    )

  def value_for_form(self, value):
    if isinstance(value, User):
        return value.pk
    else:
        print("selected q:",value)
        selectedqval=value
        print("selected qvalue:",selectedqval)
        return value

class ConditionsAnswerBlock(blocks.ChooserBlock):
  widget = Select
  class Meta:
    icon = "question"

  @cached_property
  def target_model(self):
    return Choice

  @cached_property
  def field(self):
    choice=Choice.objects.all()
    return forms.ModelChoiceField(
        queryset=choice,
        widget=self.widget,
        required=self._required,
    )

  def value_for_form(self, value):
    if isinstance(value, User):
        return value.pk
    else:
        return value

Now irrespective of the Question selection I'm getting all the Answer options

Cœur
  • 37,241
  • 25
  • 195
  • 267
Lalas M
  • 1,116
  • 1
  • 12
  • 29

1 Answers1

1

For my understanding, this is not achievable with wagtail or Django directly. This is actually a HTML question.

Wagtail and Django use pure HTML/CSS to create its UI elements. These UI elements interact with python code in wagtail/django using HTML forms submissions. That means using POST request.
Another way to interact with the python code is using redirections, meaning GET requests. But that way you can't access UI elements.

First you can have hidden choice fields for each answer group. In this case two choice fields, having Camry and Land Cruiser in one and Civic and Accord in the other one.

Then you have to write some javascript code to show/hide and required choice field when the question select event triggered. You can search for event triggers in HTML for more information.

After form is submitted, you can read the value of the question and the value of the corresponding answer field.

Ramesh-X
  • 4,853
  • 6
  • 46
  • 67