trytocode
trytocode

Reputation: 403

how to loop insert data from database to select form with django

so i want to make a dependent select box , but im still beginner and want to try with the old way

The point is , the first dropdown is the database name (schema in dbeaver) and the second dropdown is list of table name that the database has

html code

<div class="form-group">
                  <label class="control-label col-md-3">Table Name</label>
                  <div class="col-md-4">
                    <div class="input-group bootstrap-timepicker">
                       <div class="btn-group">
                            <select style="width:425px;background-color:white;height:30px;font-color:red;text-align-last:center;">              
                            <!-- <li><a href="#"></a></li> -->
                               {% for table_name in obj %}
                                <option>{{ table_name.table_name }}
                              {% endfor %}                          
                            <!-- <li><a href="#">Dropdown link</a></li> -->
                            </option>
                            </select>                    
                      </div>
                    </div>
                  </div>
                </div>
                <div class="form-group">
                  <label class="control-label col-md-3">Column Name</label>
                  <div class="col-md-4">
                    <div class="input-group bootstrap-timepicker">
                       <div class="btn-group">
                            <select style="width:425px;background-color:white;height:30px;font-color:red;text-align-last:center;">              
                            <!-- <li><a href="#"></a></li> -->


                            *here where i want to put the data after i select the first select above*



                            <!-- <li><a href="#">Dropdown link</a></li> -->
                            </option>
                            </select>                    
                      </div>
                    </div>
                  </div>
                </div>

Havent put the post and get for the first select dropdown to send the parameter *dont know where

views.py

#for  the first dropdown
def list_all_table(request):    
    obj = TableAll.objects.all()
    context = {
        'obj' : obj
    }
    return render(request,'define_segment.html',context)


#for the second dropdown form after you select the first dropdown
def list_all_table2(request):
     #need to get parameter first but how
     dsn_tns = cx_Oracle.makedsn('IP', 'PORT', sid)  
     conn = cx_Oracle.connect(user=r ' ', password=' ', dsn=dsn_tns) 
     c = conn.cursor()
     c.execute("SELECT table_name FROM ALL_TABLES WHERE owner ='"+ variable from firstdropdown +"'")
     for row in c:
        #to insert the data in second select dropdown

     return render(request,'define_segment.html',context)    

models.py

import datetime

from django.db import models
from django.utils import timezone

class TableAll(models.Model):
    table_name = models.CharField(max_length=250)

0001_init.py

from django.db import migrations, models
from django.contrib.auth.models import User
import django.db.models.deletion


class Migration(migrations.Migration):

    initial = True

    dependencies = [
    ]

    role = models.CharField(max_length=250)
    role.contribute_to_class(User,'role')    

    operations = [
         migrations.CreateModel(
            name='TableAll',
            fields=[                
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('table_name', models.CharField(max_length=250)),                
            ],
        ),
    ]

Maybe someone can help me with this, thankyou for the help !

Upvotes: 0

Views: 945

Answers (1)

Subham
Subham

Reputation: 701

You need to use ajax to implement what you want. First of all, you have to set the value as the id of the table and also give id to selectbox of table.

 <select id="tableselect" style="width:425px;background-color:white;height:30px;font-color:red;text-align-last:center;">              
      <!-- <li><a href="#"></a></li> -->
         {% for table_name in obj %}
          <option value="{{table_name.id}}">{{ table_name.table_name }}
        {% endfor %}                          
      <!-- <li><a href="#">Dropdown link</a></li> -->
         </option>
  </select>  

After that craete AJAX request using jQuery to get the table id and send to view. as below

    <script>
     $(document).ready(function() {
      $("#tableselect").change(function () {
        var url = "{% url 'load-data' %} ";  
        var table_id = $(this).val(); 
        $.ajax({                       
          url: url,                    
          data: {
            'table_id': table_id      
          },
          success: function (data) {   
            $("#dataselect").html(data);  
          }
        });

      });
      });
  </script>

then give id to selectbox of columns as below and leave the options part blank

<div class="btn-group">
    <select id="dataselect" style="width:425px;background-color:white;height:30px;font-color:red;text-align-last:center;">              


    </select>                    
</div>

after that in your urls .

 path('ajax/load-data', views.load_data, name='load-data'),

and create view to accpt table id and render options for columns for that id.

def load_data(request):
  table_id = int(request.GET.get('table_id'))
  # do something with table_id and render the options in template

  obj = yourModel.objects.filter(#... whaterwer you like with table_id )
  context= {'obj' : obj }
  return render(request, data-list.html, context)

then create an HTML template with the name data-list.html that loads the second drop-down options.

{% for data in obj %}
<option value="{{ data.id }}">{{ data.yourcolumn }}</option>
{% endfor %}

Upvotes: 2

Related Questions