Which way is possible?

Let’s say I have a form that has 2 fields, First and Last. For example, the input for First: 1 and Last : 5. Upon saving:

  1. It saves the range: 1, 2, 3, 4, 5 and stored under a single field (Num) in a database table called (Numbers), row 1 - 1, row 2 - 2, row 3 - 3, row 4 - 4, row 5 - 5 by using a view
  2. It saves the First and Last values in a table called Range. Using a view and somehow uses the numbers of 1 & 5 and derive the range of 1, 2, 3, 4, 5 and stored in another table (Numbers) where under the field (Num), row 1 - 1, row 2 - 2, row 3 - 3, row 4 - 4, row 5 - 5

Which is possible? And how do i do it? Appreciate it for any help provided

Extra: Would it also be possible to stored a additional row under Num which is a totally different field in the form. While making sure everything is link by a foreign key?

When you make a view in Django all the way you proccess the data is up to you.

For your case you can do something like:

def get_range_view(request):
    if request.method == "POST":
        form = RangeForm(request.POST)
        if form.is_valid():
            first_number = form.cleaned_data["first_number"]
            last_number = form.cleaned_data["last_number"]
            list_range = [x for x in range(first_number, last_number + 1)]

know you have the list_range list that is [1, 2, 3, 4, 5] you can iterate it and make a string or JSON Object in order to save it to the database with the format you want.

Thank you very much !

What if i change the format of first and last? Example first = 1/0/1 and last = 1/0/5. How do i get it to add so it become 1/0/1, 1/0/2, 1/0/3, 1/0/4, 1/0/5
@Rigo-Villalta

Iterating over the list:


list_range = [1, 2, 3, 4, 5]
formatted_list = []
for i in list_range:
    formatted_list.append("1/0/" + str(i))

You will have:

formatted_list
['1/0/1', '1/0/2', '1/0/3', '1/0/4', '1/0/5']

This is basic Python string and data manipulation, I encourage you to follow a Python tutorial because almost everything you will do with Django will need Python manipulation.

Sorry for a stupid question. I tend to forget the simple stuff. But i got just one more question. In my list_range, i got values from 1 to 48. How do I make sure it stop according to the last number. I tried the following but upon saving, my page just keep loading and not proceed to the next page. Can advise me where am i doing it wrong?
For firstportid0 and lastportid0, i am able to get the value of 1 and 10 for example.

firstportid0 = request.POST.get('deviceinterface_set-0-firstportid').split('/')[2]
lastportid0 = request.POST.get('deviceinterface_set-0-lastportid').split('/')[2]
list_range=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48]
if firstportid0<=lastportid0:
   formatted_list = []
   for i in list_range:
        while firstportid0<=lastportid0:
              formatted_list.append("1/0/" + str(i))
              firstportid0+=1
   print(formatted_list)

It finally loaded. The page returns me memory error

Can you show all your View?

Here is the view:

    if request.method == "POST":
        device_frm = DeviceForm(request.POST) 
        dd_form = DeviceDetailForm(request.POST)        
        di_formset = inlineformset_factory(Device, DeviceInterface, fields=('moduletype', 'firstportid', 'lastportid'),widgets={  'firstportid':TextInput(attrs={'placeholder': 'e.g. TenGigabitEthernet1/0/1'}), 'lastportid':TextInput(attrs={'placeholder':'eg. TenGigabitEthernet1/0/48'})},extra=10)
        di_form=di_formset(request.POST)        
        if device_frm.is_valid():        
            new_device = device_frm.save()            
            if dd_form.is_valid():               
                deviceD = dd_form.save(commit=False)                
                deviceD.DD2DKEY = new_device              
                deviceD.save()
                print(deviceD.mgt_interface)               
                if di_form.is_valid():                   
                    deviceI=di_form.save(commit=False)                     
                    firstportid0 = request.POST.get('deviceinterface_set-0-firstportid').split('/')[2]
                    lastportid0 = request.POST.get('deviceinterface_set-0-lastportid').split('/')[2]                    
                    list_range=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48]
                    formatted_list = []
                    if firstportid0<=lastportid0:             
                        for i in list_range:
                            #while firstportid0<=lastportid0:
                            formatted_list.append("TenGigabitEternet1/0/" + str(i))
                            #firstportid0+=1
                    print(formatted_list)
                    cursor = connection.cursor()
                    string =  'dev_interface_' + str(new_device.id)
                    # Execute your raw sql 
                    query = f"CREATE TABLE {string}(id integer NOT NULL PRIMARY KEY AUTOINCREMENT, mgt_interface varchar(50) NOT NULL, mgt_ip varchar(15) NOT NULL, interface varchar(50), description varchar(250), speed varchar(250), duplex varchar(250), status varchar(250), mode int(2), vlan varchar(50), voice_vlan varchar(50), trunk_protocol varchar(200), trunk_vlan varchar(50), mtu varchar(50), route_ip varchar(50)  );"
                    cursor.execute(query)
                    string1=deviceD.mgt_interface                   
                    string2= new_device.ipaddr
                    string3 = 'dev_route_list_' + str(new_device.id)
                    string4 = 'dev_neighbour_list_' + str(new_device.id)                    
                    #queryagain = f"INSERT INTO {string}(mgt_interface, mgt_ip) VALUES ({string1}, {string2})" #Not working
                    #cursor.execute(queryagain)
                    queryagain = f"CREATE TABLE {string3}(id integer NOT NULL PRIMARY KEY AUTOINCREMENT, mgt_ip varchar(50) NOT NULL, subnetmask varchar(15) NOT NULL, device_interface_id integer NOT NULL REFERENCES {string} DEFERRABLE INITIALLY DEFERRED  );"
                    queryagainagain = f"CREATE TABLE {string4}(id integer NOT NULL PRIMARY KEY AUTOINCREMENT, mgt_ip varchar(50) NOT NULL, device_interface_id integer NOT NULL REFERENCES {string} DEFERRABLE INITIALLY DEFERRED  );"
                    cursor.execute(queryagain)
                    cursor.execute(queryagainagain)
                    cursor.close()
                    
                    for instances in deviceI:          
                        instances.I2DKEY=new_device
                        instances.save()
                    return render(request, 'interface/device_added.html',{'devices':Device.objects.all()})
                return render(request,'interface/device_add.html',{'form':device_frm, 'dd_form': dd_form, 'di_form':di_form})
            return render(request,'interface/device_add.html',{'form':device_frm, 'dd_form': dd_form, 'di_form':di_form})
        return render(request,'interface/device_add.html',{'form':device_frm, 'dd_form': dd_form, 'di_form':di_form})
    else:
        device_frm = DeviceForm()
        dd_form = DeviceDetailForm()
        di_formset = inlineformset_factory(Device, DeviceInterface, fields=('moduletype', 'firstportid', 'lastportid'), widgets={  'firstportid':TextInput(attrs={'placeholder': 'e.g. TenGigabitEthernet1/0/1'}), 'lastportid':TextInput(attrs={'placeholder':'eg. TenGigabitEthernet1/0/48'})},extra=10)
        di_form=di_formset(queryset = DeviceInterface.objects.none())
        return render(request,'interface/device_add.html',{'form':device_frm, 'dd_form': dd_form, 'di_form':di_form})```

Ignore the raw SQL. For now I have comment out the while statement and the firstportid0+=1. So now it is just looping the whole list_range. If I uncomment it, there will be memory error

Why do you create a new table in every form submit?

U mean the raw SQL? That section is request by the one who assigned me the task. The memory error happens before that was added in

Update: Issue solved. The type of the firstportid0 and lastportid0 was in str. I convert it to int and it work