How to get Dependent Dropdown Feilds in Django ModelForms. Please answer : Important

942 views
Skip to first unread message

Sai

unread,
Jun 7, 2020, 6:34:00 AM6/7/20
to Django users
Hi guys,
I am working on a Django project, which involves submission form and saving the data in the database using model form.  I am stuck with one of the functionalities of form which should work like for example "do you want benefit plan: YES, next Field options should pop up. if click NO, nothing should happen and move to the next question."  

I went through all over the internet and found the dependent drop-down select option but not like field pop up as we click through te form.

Please let me know how to achieve this in a clear way as I am new to Django and programming as well.

Thank You so much in advance.....

wongX Ndeso

unread,
Jun 7, 2020, 10:23:33 AM6/7/20
to django...@googlegroups.com
You can use django form wizard if you want, much easier than you should manipulate the onclick event using javascript or something similar with that..
Maybe you should remodel your form or the flow.. Hope this help


--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/0c8d8457-b2d8-4598-aa0d-b9b05e817722o%40googlegroups.com.

AMINE AZIZ

unread,
Jun 7, 2020, 1:49:28 PM6/7/20
to Django users
Hi

You need to use some JQUERY code

You need this in admin or frontend ?

Shyam Acharjya

unread,
Jun 7, 2020, 1:49:30 PM6/7/20
to django...@googlegroups.com
If anyone has done this before.plese share the sollution.thnx....

Ernest Thuku

unread,
Jun 7, 2020, 1:49:33 PM6/7/20
to Django users
I think that you will have to use something like JavaScript in the model forms

--

Shyam Acharjya

unread,
Jun 7, 2020, 1:59:45 PM6/7/20
to Django users
hi AMINE AZIZ. for frontend what approach should be taken?
thnx

chaitanya orakala

unread,
Jun 7, 2020, 3:43:45 PM6/7/20
to django...@googlegroups.com
Thanks for the response guys. I see many of them are saying need to use javascript or jquery. 

Is there any reference links to achieve that? ? 

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.

AMINE AZIZ

unread,
Jun 7, 2020, 3:52:52 PM6/7/20
to Django users
You 'll use JQUERY normal as the same in html

You need every html id (so you cab add on change)

JQUERY on change select
Show hidden popup / or show hidden input

Share your code.

chaitanya orakala

unread,
Jun 7, 2020, 4:11:03 PM6/7/20
to django...@googlegroups.com
sure, here is my code. please let me know how can I modify this to achieve a dependent drop fields. 
I want it to make action on executive_authority, next fields should pop-up

Views.py
****
from django.shortcuts import render, redirect
from er_form.forms import NewClientForm, BillingGroupForm
from django.template.context_processors import csrf

def index(request):
    context = {}
    return render(request, 'er_form/index.html', context)


def client(request):
    if request.method == 'POST':
        client_form = NewClientForm(request.POST)
        billing_form = BillingGroupForm(request.POST)     #saving the instance

        if client_form.is_valid() and billing_form.is_valid():
            form = client_form.save()
            bform = billing_form.save(commit=False)     #to create relatnshp between 2forms,dont save just collect instance

            bform.form = form           #creating rltnshp between two forms
            bform.client_id=1
            bform.save()                #saving both forms

            return redirect('client')

    else:
        client_form = NewClientForm()
        billing_form = BillingGroupForm()
    args = {}
    args.update(csrf(request))
    args['client_form'] = client_form
    args['billing_form'] = billing_form

    return render(request, "er_form/client.html", args)
****
models.py
****
from __future__ import unicode_literals
from django.utils import timezone
from django.db import models
from datetime import datetime, date, timedelta
from django.core.validators import RegexValidator

# Create your models here.
#New Client model
class NewClient(models.Model):
    #choices for selection


    status_choice = [
    ('active', 'Active'),
    ('inactive', 'In-Active'),
    ]

    #User Input Feilds
    business_name = models.CharField(max_length=1024, help_text='Enter Your Business Name')
    legal_name = models.CharField(max_length=1024, help_text='Enter Legal Name, if different from the Business')
    nature_of_business = models.CharField(max_length=1024)
    years_in_business = models.PositiveIntegerField(default=0)
    company_type = models.CharField(max_length=20)
    #Data provided by Tool to reflect in Database
    association_name = models.CharField(max_length=20, default='OCIBP')
    group = models.CharField(max_length=30, default='', null=True)
    code = models.CharField(max_length=10, default='000')
    status = models.CharField(max_length=15, choices=status_choice, default='active')
    anniversery_date=models.DateTimeField(default=datetime.now()+timedelta(days=365))
    service_rep = models.CharField(max_length=50, default='Carolina')
    sales_person = models.CharField(max_length=50, default='Robert Perusco')
    renewal_agent = models.CharField(max_length=50, default='Merit Ontario')
    first_billing_period = models.DateField(auto_now_add=True)
    created_on = models.DateField(auto_now=True)
    created_by = models.DateField(null=True)
    last_updated_on = models.DateField(null=True)
    last_updated_by = models.DateField(null=True)
    current_state = models.CharField(max_length=15, default='open')
    original_service_date = models.DateField(auto_now_add=True)
    cert_length = models.PositiveIntegerField(null=True)
    cert_start = models.DateField(null=True)
    require_pin = models.CharField(max_length=15, null=True)
    require_alt_pin = models.CharField(max_length=15, null=True)





    def __str__(self):
        return self.business_name

#BillingGroup Model

class BillingGroup(models.Model):
    client = models.ForeignKey(NewClient)
    name = models.CharField(max_length=1024, default='Administration Fee')
    billing_type = models.CharField(max_length=1024, default='Per Person Charge')
    remit_to = models.CharField(max_length=1024, default = 'BSL')
    language = models.CharField(max_length=50, default='English')
    legacy_system_code = models.CharField(max_length=20, null=True)
    carrier_division_code = models.CharField(max_length=20, null=True)
    invoice_override = models.CharField(max_length=20, null=True)
    address_1 = models.CharField("Address line 1",max_length=1024,)
    address_2 = models.CharField("Address line 2",max_length=1024,)
    city = models.CharField("City",max_length=1024,)
    province = models.CharField("Province",max_length=30,)
    country = models.CharField("Country", max_length=30)
    zip_code = models.CharField("ZIP / Postal code",max_length=12,)
    first_name = models.CharField("First Name", max_length=30, )
    last_name = models.CharField("Last Name", max_length=30,)
    title = models.CharField("Title/Position", max_length=1024)
    email = models.EmailField("Authorized - Email", max_length=254)
    phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.")
    phone_number = models.CharField(validators=[phone_regex], max_length=17, blank=True) # validators should be a list
    fax = models.CharField(max_length=30, null=True)
    send_notification = models.BooleanField(default=True)
    executive_authority = models.CharField(verbose_name = "Is This Person also has Signing Authority", max_length=15,)
    exec_first_name = models.CharField("Executive First Name", max_length=30, )
    exec_last_name = models.CharField("Executive Last Name", max_length=30,)
    exec_title = models.CharField("Executive Title/Position", max_length=1024)
    exec_email = models.EmailField("Executive - Email", max_length=254)
    exec_phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.")
    exec_phone_number = models.CharField("Executive Phone Number",validators=[phone_regex], max_length=17, blank=True)
    exec_fax = models.CharField("Fax number",max_length=30, null=True)
    payment_type = models.CharField(max_length=30)
    institution_code = models.CharField(max_length=30)
    branch_number = models.CharField(max_length=30)
    account_number = models.CharField(max_length=30)
    withdraw_day = models.DateField(null=True, blank=True)
    federal_tax_province = models.CharField(max_length=30, default="Ontario")

    def __str__(self):
        return self.client
****
client.html

****
{% extends 'er_form/index.html' %}

{% block content %}
 <div class="container">
    <div class="form-group">
            <form method="POST">
            {% csrf_token %}
            {{ client_form.as_p }}
            {{ billing_form.as_p }}
            <button type="submit" class="btn btn-primary">Submit</button>
            </form>
    </div>
  </div>
{% endblock content %}

****
urls.py
***
from django.conf.urls import url
from er_form import views

urlpatterns = [
    url('', views.client, name="client"),
]
***
I am combining two model forms into a single HTML template.

Please have a look AZIZ sir


--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.

chaitanya orakala

unread,
Jun 7, 2020, 5:08:47 PM6/7/20
to django...@googlegroups.com
Can anyone suggest how to approch this???
Message has been deleted

AMINE AZIZ

unread,
Jun 7, 2020, 5:18:13 PM6/7/20
to Django users
I will share with you my iwn code used in admin , but it still the same as the front end 

withe jQuery i can show input or hide it , so you will do the same with popup , by default it will be display none, and with Jquery you can show it if user change value to yes dropdown (select)

you will use id div of pupup to show it or hide it 


if (!$) {
// Need this line because Django also provided jQuery and namespaced as django.jQuery
$ = django.jQuery;
}



$(document).ready(function() {

$("#id_paysPartenaires").change(function()
{



var total_partenaire=$("#id_multipartenairecooperationbilaterale_set-TOTAL_FORMS").val()
var SelectNumber = i
SelectedValuePartenaire=$("#id_multipartenairecooperationbilaterale_set-"+SelectNumber+"-multiPartenairePP").val()
//alert(SelectNumber)



$("[id=div-2-multiAdefinir]:eq("+SelectNumber+")").hide();
$("[id=div-2-multiGouvernementPP]:eq("+SelectNumber+")").hide();
$("[id=div-2-multiGouvernementPP]:eq("+SelectNumber+")").hide();
$("[id=div-2-multiPaysPP]:eq("+SelectNumber+")").show();
}

});

chaitanya orakala

unread,
Jun 9, 2020, 3:10:18 AM6/9/20
to django...@googlegroups.com
Thank You, Amine Aziz. I tried jquery and it worked. its so simple once we know jquery.
do help others like you did to me.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.

Balaji Shetty

unread,
Jun 9, 2020, 6:36:20 AM6/9/20
to django...@googlegroups.com
Nice

Can you please share sample code on git link.

This is very common requirement in every project 


To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAPcTzRabB90jUEuYj1v-9JWdOMqqsM4fjN-TEq1CwOcwEPX1zA%40mail.gmail.com.


--
Mr Shetty Balaji
Asst. Prof.
IT Department
SGGS I&T
Nanded. My. India

chaitanya orakala

unread,
Jun 10, 2020, 2:42:47 AM6/10/20
to django...@googlegroups.com
sure, I will do it by tomorrow


To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.


--
Mr Shetty Balaji
Asst. Prof.
IT Department
SGGS I&T
Nanded. My. India

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAECSbOt4OiS_WLAucNWQtwpWuZ_LZe1hXyM4%3DFXZzmm6mSVGHw%40mail.gmail.com.

AMINE AZIZ

unread,
Jun 10, 2020, 8:54:50 AM6/10/20
to Django users
👍🏻
Shre your code, so it will help others.
And if you can, change to resoulved, so it will be marked in Google search

Best regards

Balaji Shetty

unread,
Jun 10, 2020, 10:00:42 AM6/10/20
to django...@googlegroups.com
Thank You Very Much for considering advice



--
Mr. Shetty Balaji S.
Asst. Professor
Department of Information Technology,
SGGS Institute of Engineering & Technology, Vishnupuri, Nanded.MH.India
  Mobile: +91-7276300495

chaitanya orakala

unread,
Jun 10, 2020, 7:52:07 PM6/10/20
to django...@googlegroups.com
Answer :

First hide the necessary fields which you want  to hide and pop in drop down.
style.css
****
#id_exec_first_name, label[for="id_exec_first_name"] {
  display: none
}

#id_exec_last_name, label[for="id_exec_last_name"]{
display: none
}

#id_exec_title, label[for="id_exec_title"]{
display: none
}

#id_exec_email, label[for="id_exec_email"]{
display: none
}

#id_exec_phone_number, label[for="id_exec_phone_number"]{
display: none
}

#id_exec_fax, label[for="id_exec_fax"]{
display: none
}

#li{
list-style: none;
}

****


Include jquery CDN and write a function to make fields display which is hidden, grad id fields from inspect element.
Html
***
{% extends 'er_form/index.html' %}



{% block content %}


<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"
integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>

<script>
$(function () {

 $('#id_executive_authority_1').on('click', function () {
 $('#id_exec_first_name, label[for="id_exec_first_name"]').show();
 $('#id_exec_last_name, label[for="id_exec_last_name"]').show();
 $('#id_exec_title, label[for="id_exec_title"]').show();
 $('#id_exec_email, label[for="id_exec_email"]').show();
 $('#id_exec_phone_number, label[for="id_exec_phone_number"]').show();
 $('#id_exec_fax, label[for="id_exec_fax"]').show();

});
});


$(function () {

 $('#id_executive_authority_0').on('click', function () {
 $('#id_exec_first_name, label[for="id_exec_first_name"]').hide();
 $('#id_exec_last_name, label[for="id_exec_last_name"]').hide();
 $('#id_exec_title, label[for="id_exec_title"]').hide();
 $('#id_exec_email, label[for="id_exec_email"]').hide();
 $('#id_exec_phone_number, label[for="id_exec_phone_number"]').hide();
 $('#id_exec_fax, label[for="id_exec_fax"]').hide();

});
});


</script>


 <div class="container">
    <div class="form-group">
            <form method="POST">
            {% csrf_token %}
            {{ client_form.as_p }}
            {{ billing_form.as_p }}
            <button type="submit" class="btn btn-primary">Submit</button>
            </form>
    </div>
  </div>
{% endblock content %}


***



chaitanya orakala

unread,
Jun 20, 2020, 12:59:39 AM6/20/20
to django...@googlegroups.com
Hi guys,
I made a video on how to solve this problem.
here is the Link 

chaitanya orakala

unread,
Jun 20, 2020, 1:01:25 AM6/20/20
to django...@googlegroups.com
Hi guys,
I made a video on how to solve this problem.
Please go to the link below and subscribe for more content.


There is a git repo link in the description as well.

Thank You



On Wed, Jun 10, 2020 at 3:50 PM chaitanya orakala <chaitu....@gmail.com> wrote:
Reply all
Reply to author
Forward
0 new messages