Struggling to incorporate hidden and visible features using Django framework

One of my unique functionalities is that I contain a radio button in my form. If the user clicks "Yes," an error message will be displayed on the screen indicating that this is not the correct place to submit data, and suggesting that they visit another website.

However, if the user clicks "No," all other fields in the form should become visible and mandatory.

One issue I currently face is that when the user clicks "No" and attempts to submit the form without filling in all the required fields, the form gets reloaded and the fields are hidden once again. While the data is not saved in the database, upon clicking "No" again, the fields are displayed with errors highlighted.

The main concern is that when the user clicks "No" and all fields are displayed, I do not want them to be hidden again until the form is successfully submitted or the user clicks "Yes." I am seeking a solution that will only reload the form when all fields are correctly filled and submitted to the database.

Below, I have included the code I have written so far for better understanding:

1) models.py

 // Code for models.py

2) forms.py

 // Code for forms.py

3) Javascript / jQuery logic

 // Code for Javascript / jQuery logic

Any assistance or advice on this matter would be greatly appreciated!

Answer №1

If you want dynamic logic after your template has loaded, you will need to use JavaScript instead of Django. Django processes your request once and sends it to your web browser, so if you only use Django to show and hide things, you will have to reload your page each time.

Create a JavaScript function (or use jQuery if you're a beginner, as it is easier to grasp) to implement the logic for showing or hiding inputs.

https://www.w3schools.com/jS/default.asp

https://www.w3schools.com/Jquery/default.asp

EDIT: To prevent your form from continuously sending data to the backend without validation, you should stop the default action. Here's how you can do it:

$("#btn_submit").click((e) => {
    e.preventDefault(); // This will prevent the button from submitting
    ... // Validate your logic here
    $("#form_id").submit()
});

When it comes to hiding and showing elements, it's quite simple to achieve:

$("#chk_a").click(function(e){
    if(this.checked) {
        $(".group_b").hide(); // hide everything from group B

        $("#input_a").show();
        $("#button_a").show();
        $("#somethingelse_a").show();
    }
});

// Same logic for group B elements

<input id="chk_a">
<input id="input_a" class="group_a">
<input id="button_a" class="group_a">
<input id="somethingelse_a" class="group_a">

<input id="chk_b">
<input id="input_b" class="group_b">
<input id="button_b" class="group_b">
<input id="somethingelse_b" class="group_b">

Answer №2

I successfully addressed my concern by introducing an additional hidden field into the solution implementation. Feel free to refer to the following steps for the resolution:

1) To include a hidden field in forms.py, use the code snippet below:

source = forms.CharField(max_length=50, widget=forms.HiddenInput(), required=False)

2) Revised JavaScript / jQuery logic:

<script>
    $(document).ready(function () {
        //hide all
        if($("#id_source").val()!="postback" ) {
            $(".hidden-md").hide();
            $(".hidden-lg").hide();
            $(".hidden-xs").hide();
            $("#id_source").val("postback");
        }

        if ($('#id_field2_0').is(':checked') || $("input[name='field2']").is(':checked') == false) {
            $(".hidden-md").hide();
            $(".hidden-lg").hide();
            $(".hidden-xs").hide();
            $("input[name='field5']").prop('checked', false);
            $("input[name='field7']").prop('checked', false);   
        }

        if ($("input[name='field5']").is(':checked') == false || $('#id_field5_1').is(':checked')) {
            $(".hidden-lg").hide(); 
            $("#id_field6").html('');
        }

        if ($("input[name='field7']").is(':checked') == false || $('#id_field7_1').is(':checked')) {
            $(".hidden-xs").hide(); 
            $("#id_field8").html('');
        }

        $("input[name='field2']").click(function () {//change event on radio button
            if (this.value == 'No') {
                $(".hidden-md").show();     
            }
            else {
                $(".hidden-md").hide();
                $(".hidden-lg").hide();
                $(".hidden-xs").hide(); 
                $("input[name='field5']").prop('checked', false);
                $("input[name='field7']").prop('checked', false);
            }
        });

         $("input[name='field5']").click(function () {//click event on radio button
            if (this.value == 'Yes') {
                $(".hidden-lg").show();
            }
            else {
                $(".hidden-lg").hide();
                $("#id_field6").html('');
            }
        });

        $("input[name='field7']").click(function () {//click event on radio button
            if (this.value == 'Yes') {
                $(".hidden-xs").show();
            }
            else {
                $(".hidden-xs").hide();
                $("#id_field8").html('');
            }
        });
    });
</script>

By utilizing the above approach, I have effectively integrated hide and show capabilities using jQuery and Django. Despite the form being reloaded, this method resolves my issue and meets the desired functionality requirements.

Best regards,

Amey Kelekar

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

Obtaining a roster of file names with the help of the Glob

I'm attempting to gather a list of file names in node, however I believe I am encountering a scoping problem. var files = []; glob(options.JSX_DEST + "/*.js", function (er, files) { files = files.map(function(match) { return path.relati ...

What is the recommended approach for embedding scripts within Angular templates?

I am working on an Angular SPA that consists of multiple tabs, each served by templates. Depending on the tab, different scripts (both local and CDN) are required. Therefore, I am looking for a way to load these scripts only when they are needed, which mea ...

Strategies for iterating over an array in React with TypeScript

I'm currently working on looping through an array to display its values. Here's the code I have: ineligiblePointsTableRows() { return this.state[PointsTableType.INELIGIBLE].contracts.map(contract => { return { applied: (&l ...

Functionality limited to Firefox browser

I'm having some trouble with my website development in HTML5 and CSS3. Specifically, I am struggling to get my processing sketch to work on browsers other than Firefox. Below is the code I am working with: <!DOCTYPE html> <html> ...

Django view returns incorrect HTML template after receiving AJAX GET request from jQuery

In my web application built with Django, the index.html page utilizes jquery fullcalendar to display events. These events are populated by a Django view called index() which uses simplejson to dump an array containing all events for the current month. The ...

Enhancing fancybox with dynamic scrollbars as the window size changes

I'm currently working on a popup form that I'm displaying with Fancybox 2 by using the code below: $(link).fancybox({ type: 'iFrame', autoSize: false, autoScale: false, width: '1280px', height: '1024p ...

Php/JavaScript Error: Identifier Not Found

I've double-checked my code multiple times, but it still doesn't seem to be working properly. When the PHP runs, the browser console displays the following error: Uncaught SyntaxError: Unexpected identifier. I'm not sure if this is a si ...

Invoking Jquery on the server side in an asp.net environment

I am interested in incorporating this plugin into my asp.net application. I am currently serializing the title and text server-side using this class, which I have successfully implemented. However, I am faced with a challenge: I need to load titles and con ...

The phrase 'nodemon' is not identified as a valid cmdlet, function, script file, or executable program

Recently I started working with Node.js, but I encountered an error when trying to run a program. The error message says "the term nodemon is not recognized the name of cmdlet, function, script file or operable function". Can someone please assist me with ...

Interacting with a non-stringified object displayed in the browser console using TestCafe

Upon receiving a page that logs an object to the console, I encountered an issue when trying to access this object using getBrowserConsoleMessages(). The object appeared as the String "[object Object]" in the console, making it impossible for me to parse ...

When attempting to load the table from JSON, the error message "Cannot read property 'name' of null" occurs in the fooplugins/Footable plugin

I am facing an issue while trying to integrate the "FooTable" plugin with ajax calls. Everything works perfectly fine when I directly input the JSON data or load it from a JSON file using $.get('....json'). However, when attempting to fetch the t ...

how can I use jQuery to disable clickable behavior in HTML anchor tags?

Here is the HTML code I am working with: (note -: I included j library on the top of page ) <div class="WIWC_T1"> <a href="javascript:void(0);" onClick="call_levelofcourse();popup('popUpDiv1')">Level of Course</a> </di ...

How can I schedule a recurring task in celery once a task is completed?

In my current django project, I have set up a celery beat schedule to run a task periodically on a timer. The task involves making about 250 requests to a URL that returns JSON data. Due to request limitations, the entire task can take anywhere from 5 to 1 ...

Sorting columns containing English, Japanese entries, and null values using a customized sorting algorithm in MUI Data Grid is a straightforward process

I am working with an MUI data grid and I am looking to implement a custom sorting algorithm for columns that can override the default options provided by MUI. The data in my fields is in English, Japanese, as well as empty/null values. My desired output sh ...

Update the label for the weekday on Material UI picker

Is there a way to change the weekday display in Material UI DatePicker from single initial (M, T, W, T, F, S, S) to three-letter initials (MON, TUE, WED, etc)? I want to customize it in my component like this: <DatePicker disablePast disableTool ...

Issue detected in JSONP request EXCLUSIVELY BY Firefox extension

It's strange that the error I'm experiencing only occurs in the Firefox extension I've linked at the bottom of this post. I've tried reproducing the error in other settings, but it just doesn't happen. Here is the AJAX request I&a ...

Discover instances of a string within an array using JQuery

I am currently exploring how to locate occurrences of a specific string within an array on the client side. The examples provided on the JQuery Docs all seem focused on number comparisons, which isn't quite what I need. Essentially, I'm attempti ...

Using an AJAX request to edit a record directly without the need for a

When updating a record, I typically utilize CRUD operations and a store setup similar to the following: storeId: 'storeId', model: 'model', pageSize: 10, autoLoad: true, proxy: { typ ...

Is there an optimal method for transforming HTML to PostScript in Java?

Is there an optimal method in Java to convert HTML with CSS2 support into a PostScript file? ...

Display the full price when no discount is available, but only reveal the discounted price when Vue.js is present

In my collection of objects, each item is structured like this: orders : [ { id: 1, image: require("./assets/imgs/product1.png"), originalPrice: 40, discountPrice: "", buyBtn: require(&q ...