Creating a dynamic form in Django using a ChoiceField is a fantastic way

I'm currently in the process of developing my initial web application using django. I am encountering difficulties when it comes to implementing a dynamic form that generates different outputs based on the selected choice.

For instance, if the measure choice is qualitative, I would like the form to remain the same without any additional fields. However, if quantitative is selected, I wish for the template to display two extra fields (value_min and value_max).

Click here to view the first option with qualitative value selection

Alternatively, click here to see the second option when quantitative value is chosen

Your assistance in this matter is greatly appreciated...

Answer №1

To handle conditions in frontend, instead of using Django tags, you can utilize JavaScript. In my usual approach, I hide the min and max values initially by setting style.display to "None", then attach an onChange event listener to the selector (e.g., Mesure) and use JavaScript to check conditions and display the values as needed by changing style.display to block.

  • Hide initial values for min and max (style.display = "None")
  • Attach an addEventListener for onChange on the selector
  • Use JavaScript to check conditions and adjust style.display accordingly

Answer №2

Forms within Django templates are generated prior to the page loading, preventing direct manipulation by users.

When creating a form in Django, you have the ability to assign classes to specific form fields, allowing for customization such as hiding certain fields.

For example, utilizing

value_min = forms.CharField(widget=forms.TextInput(attrs={'class':'hide'}))

You can also implement form checks using the clean method:

class MYform(forms.Form):
     #....
     def clean_min_value(self):
       #perform validation here based on field input
       #return value or blank as needed

Additionally, validators can be added to ensure that a value is set only when a specific choice is selected, like so:

value_min = forms.CharField(widget=forms.TextInput(attrs={'class':'hide'}), validators=[check_choice])

def check_choice(Value):
   #validate Value according to chosen criteria

Answer №3

Shoutout to @videap and @Rhea for their assistance! Thanks to their guidance, I successfully resolved my issue by implementing the suggestions from videap as well as referencing the thread Show and hide dynamically fields in Django form

The solution involved the following steps:

For the form :

class NewCriterioForm(forms.ModelForm):
    parent = TreeNodeChoiceField(queryset=Criteria.objects.all())
    def __init__(self,*args,**kwargs):
        super().__init__(*args,**kwargs)
        
        self.criteria_CHOICES = [('FunCriteria','FunCriteria'),('nonFunCriteria','nonFunCriteria')]
        self.mesure_CHOICES = (('Quantitative','Quantitative'),('Qualitative','Qualitative'))
        self.fields['parent'].label=''
        self.fields['parent'].required=False
        self.fields['type']= forms.CharField(widget=forms.Select(choices=self.criteria_CHOICES))
        self.fields['mesure']= forms.ChoiceField(choices=self.mesure_CHOICES)
    class Meta:
        model = Criteria
        fields = ('name', 'parent', 'type','slug','description','mesure','value_min','value_max')

        }

For the view :

......
criterion = NewCriterioForm()
    return render(request, 'addCriteria.html', {'criterion': criterion})

Finally, in the template , the following code was added:

              <script>
                function Hide() {
                    if(document.getElementById('id_mesure').options[document.getElementById('id_mesure').selectedIndex].value == "Qualitative") {
                         document.getElementById('id_value_min').style.display = 'none';
                         document.getElementById('id_value_max').style.display = 'none';
                    } else {
                         document.getElementById('id_value_min').style.display = '';
                         document.getElementById('id_value_max').style.display = '';
                    }
                }
                
                window.onload = function() {
                    document.getElementById('id_mesure').onchange = Hide;
                };
                </script>
               
                <div>
                    {{ criterion.name.label_tag }}{{ criterion.name }}
                </div>
                <tr></tr>
                <div>
                    {{ criterion.parent.label_tag }}{{ criterion.parent }}
                </div>
                <div>
                    {{ criterion.type.label_tag }}{{ criterion.type }}
                </div>

                <div>
                  {{ criterion.slug.label_tag }}{{ criterion.slug }}
                 </div>
                 <div>
                  {{ criterion.description.label_tag }}{{ criterion.description }}
                  </div>
                  <div>
                  {{ criterion.mesure.label_tag }}{{ criterion.mesure }}
                  </div>

                <div id="id_value_min">
                {{ criterion.value_min.label_tag }}{{ criterion.value_min }}
                </div>
                  <div id="id_value_max">
                    {{ criterion.value_max.label_tag }}{{ criterion.value_max }}
                 </div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The UserForm object cannot be converted to JSON format

I'm currently working on a django application and encountering an error: TypeError: Object of type UserForm is not JSON serializable Here's the relevant code snippet: forms.py: from django import forms from .models import Profile from django. ...

Choose the default text option for your AngularJS dropdown menu

I am facing an issue with my angularjs dropdownlist that is using ng-options. <select ng-options="perlocation.name for perlocation in locations" ng-model="locationDropdown"> Even though my dropdown list loads correctly, the selected option 0 is dis ...

What is the best way to cancel an upload file to the server and delete the file (before the upload is completed) when utilizing AJAX post requests for file uploads?

Is there a way to cancel an upload file to the server and delete the file if the upload is not finished, when using AJAX post requests for uploading files? Here is my AJAX upload code: $.ajax({ url: 'example.php', dataType: 'text&a ...

How to Use Radio Buttons in Material-UI to Disable React Components

Just starting out with ReactJS and Material-UI, I've been experimenting with them for about 3 weeks. Currently, I'm facing a challenge where: - There are 2 radio buttons in a group and 2 components (a text field and a select field); - The goal is ...

The animation glitches out when attempting to update the color of the imported model

I'm facing an issue with a Blender model that has animation. After uploading it to the site, the animation works perfectly. However, I'm trying to change the body color of the model, and when I attempt to do so, the body stops animating and becom ...

Facebook and the act of liking go hand in hand, growing together

I am working on a website where I want to include Facebook like and share buttons with counters. To achieve this, I used Facebook's own links to generate these buttons for the specific URL. The issue I encountered is that when I like or share the page ...

Tips for creating a nested div structure using JavaScript

I am facing an issue with my results object that includes data like Creation_date and approval_date. I have put the results in a loop in JavaScript and created nested divs. However, when I debug it, the divs are not nested as expected. Each one seems to ...

Change the runat attribute in JavaScript to execute on the server side

Is there a way to dynamically set the runat attribute using client-side JavaScript? I am facing the challenge of adding rows to a table after the page is loaded and must ensure that their cell data is accessible on the server side. While I am open to marki ...

Error Management in Django and Gunicorn

When encountering errors, I am looking to implement logging in Django and Gunicorn as part of my study using TDD with Python. For more information on setting up logging, please refer to Here is the code snippet: /etc/init/gunicorn-superlists-staging.mysi ...

Guide on generating a PDF on the client side and opening it in a new browser tab using AngularJS

In need of assistance with creating a PDF file on the client side using AngularJS and downloading it in a new tab on the browser. Any suggestions on how to achieve this task? ...

Error encountered during Django migration: The field 'name' does not contain a default value

Recently, I upgraded my Django application from version 1.4.5 to 1.11.16. The application was previously running on an older version of Debian Linux, which has since been reinstalled and is now at version 9.6. Originally, the database was MySQL (the defaul ...

Running unit tests in Django - implementing multiple patches for external API requests

I have a task to write a test code that interacts with an external API and requires making two requests. First, I need to validate the user. This validation is handled using a decorator in ./users/utils.py import requests def login_decorator(func): d ...

Can a single file in NextJS 13 contain both client and server components?

I have a component in one of my page.tsx files in my NextJS 13 app that can be almost fully rendered on the server. The only client interactivity required is a button that calls useRouter.pop() when clicked. It seems like I have to create a new file with ...

What is the best way to extend a class in NestJS from another class?

I've encountered an issue while attempting to extend a class service from another class service in NestJS and utilize DI to load it in a third service. The error message I'm receiving from Nest is: Error: Nest can't resolve dependencies of ...

I am struggling to get the pop-up to close using the current code. I suspect that the issue might be related to the variable I was previously using in WordPress. I have made changes but the pop-up

While delving deeper into the realm of Javascript, I encountered a stumbling block with a single popup intended for the main page of a WordPress website I am constructing. Despite my attempts to modify the code's variables, they seem unyielding. Surpr ...

Inner output not displaying on the screen

Based on the outcome of the graphql query, certain items are generated within the function contact export const Whitelist: React.FunctionComponent = (props) => { const [userData, setUserData] = useState<UsersQueryHookResult>(''); c ...

Transfer Image File to Server

Having a slight issue with uploading image files to the server This is the JavaScript code for sending files to the server using AJAX /** * * Initialize Cropping Image * */ $('input[type=file]').change(function(){ ...

Grin schedule module JSON stream

I have integrated a Smile timeline widget on my website and successfully customized it following several tutorials. However, I am struggling to utilize a Json service instead of relying on data stored in a global variable within a JavaScript file. Despite ...

JavaScript Asynchronous Functions Not Handling Await Calls Correctly

The two fadeInList functions control the fading animation of a continuous list split into two lines. The typeOutText function displays text and is supposed to execute List1 first, wait for it to finish, and then proceed with List2. However, after adding ke ...

What is the best way to input information into my Google spreadsheet with React JS?

After using https://github.com/ruucm/react-google-sheets as a reference, I encountered a persistent gapi 404 error whenever I tried to run the code. It seems like the GitHub link might not exist, causing my app to fail. However, I could be mistaken. Is t ...