# Saving 2 models within a single form

**URL:** <https://forum.djangoproject.com/t/saving-2-models-within-a-single-form/9049>\
**Category:** Using Django\
**Created:** [August 2, 2021, 9:35am UTC](https://forum.djangoproject.com/t/saving-2-models-within-a-single-form/9049 "2021-08-02T09:35:46Z")\
**Posts on this page:** 10\
**Page:** 1

<div class="post-metadata">

**Author:** ![CalvinTheCat](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/calvinthecat/32/5343_2.png) [@CalvinTheCat](https://forum.djangoproject.com/u/CalvinTheCat)\
**Post date:** [August 2, 2021, 9:35am UTC](https://forum.djangoproject.com/t/saving-2-models-within-a-single-form/9049/1 "2021-08-02T09:35:46Z")

</div>

Hello everyone, Im quite new in django and I have a problem which i took almost a week and it is still not solved. I have a form that is required to save 3 different models at once but currently I am stuck on getting the 2 model. Appreciate if anyone could solve this.  
This are my codes :  
(In views.py)

def device\_add(request):

```
if request.method == "POST":

    device_frm = DeviceForm(request.POST)

    dd_form = DeviceDetailForm(request.POST)

    if device_frm.is_valid():

        device_frm.save() #Saving form details : Hostname & Ipaddr

        deviceid = Device.objects.aggregate(Max('id')) #Getting the ID of saved row for Hostname & Ipaddr

        device = Device.objects.all() ##Part A1

        if dd_form.is_valid():

            deviceD = dd_form.save(commit=False)

            deviceD.device = Device.objects.get(id=deviceid)

            deviceD.save()

        

    return render(request, 'interface/device-added.html',{'devices':device})

       

else:

    device_frm = DeviceForm()

    dd_form = DeviceDetailForm()

    di_frm = DeviceInterfaceForm()

    return render(request,'interface/device_add.html',{'form':device_frm, 'dd_form': dd_frm})

```

(models.py)

class Device(models.Model):

```
hostname = models.CharField(max_length=50)

ipaddr = models.CharField(max_length=15)

date_added = models.DateTimeField(default=timezone.now)

def __str__ (self):

    return self.hostname

```

class DeviceDetail(models.Model):

```
hostname = models.CharField(max_length=50)

mgt_interface = models.CharField(max_length=50)

mgt_ip_addr = models.CharField(max_length=30)

subnetmask = models.CharField(max_length=30)

ssh_id = models.CharField(max_length=50)

ssh_pwd = models.CharField(max_length=50)

enable_secret = models.CharField(max_length=50)

device_model = models.ForeignKey(Device, related_name='Device', on_delete=models.CASCADE)

def __str__ (self):

    return self.hostname

```

(forms.py)

class DeviceForm(ModelForm):

```
class Meta:

    model= Device

    fields= ['hostname', 'ipaddr'] ##Part A1: date_added is not required as it's value is set by default=timezone.now() in models.py

```

class DeviceDetailForm(ModelForm):

```
class Meta:

    model= DeviceDetail

    fields= ['hostname', 'mgt_interface', 'mgt_ip_addr', 'subnetmask', 'ssh_id', 'ssh_pwd', 'enable_secret', 'device_model']

def clean(self):

    cleaned_data = super().clean()

    hostname = cleaned_data.get('hostname')

    if len(hostname) < 8:

        raise forms.ValidationError(f'Hostname needs to be more than 8 character long, {hostname}')

    return cleaned_data

```

(device\_add.html)

{% block content %}

```
            <div class="content-page">

                <div class="content">

                    

                    <!-- start page title -->

                    <div class="row">

                        <div class="col-12">

                            <div class="page-title-box">

                                <div class="page-title-right">

                                    <button type="button" class="btn btn-light mb-2 mr-1">Download Template</button>

                                <!--

                                    <ol class="breadcrumb m-0">

                                        <li class="breadcrumb-item"><a href="javascript: void(0);">Hyper</a></li>

                                        <li class="breadcrumb-item"><a href="javascript: void(0);">eCommerce</a></li>

                                        <li class="breadcrumb-item active">Devices</li>

                                    </ol>

                                -->

                                </div>

                                <h4 class="page-title">Add Device</h4>

                            </div>

                        </div>

                    </div>     

                    <!-- end page title --> 

                    <div class="row">

                        <div class="col-12">

                            <div class="card">

                                <div class="card-body">                                   

                                    <!--<form action="#"> -->

                                        

                                        <form action="/device_add/" method="post"> {% csrf_token %}

                                            <div class="row">

                

                                            </div>

                                            <div class="row">

                                                <div class="col-md-5">

                                                    <div class="form-group">

                                                        <label for="{{form.hostname.id_for_label}}">Hostname</label>

                

                                                        {{form.hostname}}

                                                        <!-- Fieldame in model -->

                                    

                                                        <!-- <input class="form-control" type="text"

                                                            id="{{device_frm.hostname.id_for_label}}"

                                                            name="{{device_frm.hostname.name}}" placeholder=""> -->

                                                    </div>

                                                </div>

                                                <div class="col-md-5">

                                                    <div class="form-group">

                                                        <label for="{{dd_form.mgt_interface.id_for_label}}">Management Interface</label>

                                                        {{dd_form.mgt_interface}}

                                                    </div>

                                                </div>

                                            </div>

                

                                            <div class="row">

                                                <div class="col-md-5">

                                                    <div class="form-group">

                                                        <label for="{{form.ipaddr.id_for_label}}">IP Address</label>

                                                        {{form.ipaddr}}

                                                    </div>

                                                </div>

                                                <div class="col-md-5">

                                                    <div class="form-group">

                                                        <label for="{{dd_form.mgt_ip_addr.id_for_label}}">Management IP Address<span

                                                                class="text-danger">*</span></label>

                                                        {{dd_form.mgt_ip_addr}}

                                                    </div>

                                                </div>

                                                <div class="col-md-2">

                                                    <div class="form-group">

                                                        <label for="{{dd_form.subnetmask.id_for_label}}">Subnet Mask Bit<span

                                                                class="text-danger">*</span></label>

                                                        <select class="custom-select mb-3" name="{{dd_form.subnet_bit}}">

                                                            <option selected>Select</option>

                                                            <option value="16">16</option>

                                                            <option value="17">17</option>

                                                            <option value="18">18</option>

                                                            <option value="19">19</option>

                                                            <option value="20">20</option>

                                                            <option value="21">21</option>

                                                            <option value="22">22</option>

                                                            <option value="23">23</option>

                                                            <option value="24">24</option>

                                                            <option value="25">25</option>

                                                            <option value="26">26</option>

                                                            <option value="27">27</option>

                                                            <option value="28">28</option>

                                                            <option value="29">29</option>

                                                            <option value="30">30</option>

                                                        </select>

                                                    </div>

                                                </div>

                                            </div>

                

                                            <div class="row">

                                                <div class="col-md-5">

                                                    <div class="form-group">

                                                        <label for="{{dd_form.ssh_id.id_for_label}}">SSH/Telnet ID<span

                                                                class="text-danger">*</span></label>

                                                        {{dd_form.ssh_id}}

                                                    </div>

                                                </div>

                                            </div>

                

                                            <div class="row">

                                                <div class="col-md-5">

                                                    <div class="form-group">

                                                        <label for="{{dd_form.ssh_pwd.id_for_label}}">SSH/Telnet Password<span

                                                                class="text-danger">*</span></label>

                                                        <div class="input-group input-group-merge">

                                                            {{dd_form.ssh_pwd}}

                                                            <div class="input-group-append" data-password="false">

                                                                <div class="input-group-text">

                                                                    <span class="password-eye"></span>

                                                                </div>

                                                            </div>

                                                        </div>

                                                    </div>

                                                </div>

                                                <div class="col-md-5">

                                                    <div class="form-group">

                                                        <label for="{{dd_form.enable_secret.id_for_label}}">Enable Secret<span

                                                                class="text-danger">*</span></label>

                                                        <div class="input-group input-group-merge">

                                                            {{dd_form.enable_secret}}

                                                            <div class="input-group-append" data-password="false">

                                                                <div class="input-group-text">

                                                                    <span class="password-eye"></span>

                                                                </div>

                                                            </div>

                                                        </div>

                                                    </div>

                                                </div>

                                            </div>

                

                                            <div class="row">

                                                <div class="col-md-5">

                                                    <div class="form-group">

                                                        <label for="{{dd_form.device_label.id_for_label}}">Model<span

                                                                class="text-danger">*</span></label>

                                                        <select class="custom-select mb-5" name="{{dd_form.device_label.name}}">

                                                            <option selected>Select</option>

                                                            <option value="Catalyst 9606R">Catalyst 9606R</option>

                                                            <option value="C9300L-48T-4X">C9300L-48T-4X</option>

                                                        </select>

                                                    </div>

                                                </div>

                                            </div>

                

                                        <div id ="firstrow">

                                        <div class = "rowsdiv">

                                        <div class="row">

                                            <div class="col-md-2">

                                                <div class="form-group">

                                                        <label for="model">Module ID</label>

                                                        <select class="custom-select mb-3">

                                                            <option selected>Select</option>

                                                            <option value="1">1</option>

                                                            <option value="2">2</option>

                                                            <option value="3">3</option>

                                                            <option value="4">4</option>

                                                            <option value="5">5</option>

                                                            <option value="6">6</option>

                                                            <option value="7">7</option>

                                                            <option value="8">8</option>

                                                            <option value="9">9</option>

                                                            <option value="10">10</option>

                                                            <option value="11">11</option>

                                                            <option value="12">12</option>

                                                            <option value="13">13</option>

                                                            <option value="14">14</option>

                                                            <option value="15">15</option>

                                                            <option value="16">16</option>

                                                            <option value="17">17</option>

                                                            <option value="18">18</option>

                                                            <option value="19">19</option>

                                                            <option value="20">20</option>

                                                        </select>  

                                                </div>

                                            </div>

                                            <div class="col-md-4">

                                                <div class="form-group">

                                                    <label for="mgt_ip">First Port ID</label>

                                                    <input class="form-control" type="text" id="port_id_start" placeholder="e.g. TenGigabitEthernet1/0/1" >

                                                </div>

                                            </div>

                                            <div class="col-md-4">

                                                <div class="form-group">

                                                    <label for="mgt_ip">Last Port ID</label>

                                                    <input class="form-control" type="text" id="port_id_end" placeholder="e.g. TenGigabitEthernet1/0/48" >

                                                </div>

                                            </div>

                                            <div class="col-md-1">

                                                <div class="form-group">

                                                    <div class="text-sm-center">

                                                    <br />

                                                    <button type="button" class="btn btn-outline-success btn-rounded" onclick = "addrow();"><i class="dripicons-plus"></i></button>

                                                    </div>

                                                </div>

                                            </div>

                                            <div class="col-md-1">

                                                <div class="form-group">

                                                    <div class="text-sm-center">

                                                    <br />

                                                    <button type="button" class="btn btn-outline-danger btn-rounded" onclick = "removerow();"><i class="dripicons-minus"></i></button>

                                                    </div>

                                                </div>

                                            </div>

                                        </div>

                                        </div>

                                        </div>

                                        <!--more rows-->

                                        <div id ='morerows'>

                                        </div>

                                        <!--more rows-->

                                        <div class="row"><br /></div>

                                        <div class="row">

                                            <div class="col-md-12">

                                                <div class="text-sm-right">

                                                <button class="btn btn-outline-secondary" type="submit">Save</button>

                                                <button class="btn btn-outline-secondary" type="reset">Clear</button>

                                                </div>

                                            </div>

                                        </div>

                                    </form>

                                </div>

                            </div>

                        </div>

                    </div> <!-- end card-body-->

                </div> <!-- end card-->

            </div> <!-- end col -->

        </div>

        <!-- end row -->

    </div> <!-- End Content -->

```

{% endblock content %}

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [August 2, 2021, 11:47am UTC](https://forum.djangoproject.com/t/saving-2-models-within-a-single-form/9049/2 "2021-08-02T11:47:44Z")

</div>

A quick note: When posting code (or HTML, or CSS) here, please enclose each block of code between lines of three backtick - ` characters. This means you’ll have a line of ```, then your code, then another line of ```. This directs the forum software to maintain the proper formatting of your code which is critical with Python. (Rather than reposting your code, you can edit your original message to add the ``` before and after each file.)

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [August 2, 2021, 11:51am UTC](https://forum.djangoproject.com/t/saving-2-models-within-a-single-form/9049/3 "2021-08-02T11:51:12Z")

</div>

> [@CalvinTheCat](#):
>
> currently I am stuck on getting the 2 model.

What **specifically** is the problem?

What is happening that you’re not expecting to have happen, or what isn’t happening that you’re expecting to see happen?

Are you getting any error messages? If so, please provide the complete traceback.

---

<div class="post-metadata">

**Author:** ![CalvinTheCat](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/calvinthecat/32/5343_2.png) [@CalvinTheCat](https://forum.djangoproject.com/u/CalvinTheCat)\
**Post date:** [August 3, 2021, 1:14am UTC](https://forum.djangoproject.com/t/saving-2-models-within-a-single-form/9049/4 "2021-08-03T01:14:49Z")

</div>

The problem is that 2nd table is not saving anything. I am require of saving the details in the form to 2 table. Eg: hostname & ipaddr to a table called Device. Then extracting the row number for this hostname & ipaddr on the table Device, add it into another table called Device\_detail on the same row number for the others like mgmt\_interface, mgt\_ip\_addr.

There is no error appearing currently. The page loads as intended but the table is not getting saved.

---

<div class="post-metadata">

**Author:** ![CalvinTheCat](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/calvinthecat/32/5343_2.png) [@CalvinTheCat](https://forum.djangoproject.com/u/CalvinTheCat)\
**Post date:** [August 3, 2021, 1:18am UTC](https://forum.djangoproject.com/t/saving-2-models-within-a-single-form/9049/5 "2021-08-03T01:18:42Z")

</div>

Thanks but it doesnt work for me :0

---

<div class="post-metadata">

**Author:** ![CalvinTheCat](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/calvinthecat/32/5343_2.png) [@CalvinTheCat](https://forum.djangoproject.com/u/CalvinTheCat)\
**Post date:** [August 3, 2021, 3:51am UTC](https://forum.djangoproject.com/t/saving-2-models-within-a-single-form/9049/6 "2021-08-03T03:51:42Z")

</div>

I added a code to check if dd\_form is valid or not and print valid or not valid on powershell and it is printing not valid. I dont know how to solve this issue

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [August 3, 2021, 4:14am UTC](https://forum.djangoproject.com/t/saving-2-models-within-a-single-form/9049/7 "2021-08-03T04:14:29Z")

</div>

You can get more details by [printing the individual error messages](https://docs.djangoproject.com/en/3.2/ref/forms/api/#django.forms.Form.errors) from the form or [rendering them on your page.](https://docs.djangoproject.com/en/3.2/topics/forms/#rendering-form-error-messages)

---

<div class="post-metadata">

**Author:** ![CalvinTheCat](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/calvinthecat/32/5343_2.png) [@CalvinTheCat](https://forum.djangoproject.com/u/CalvinTheCat)\
**Post date:** [August 3, 2021, 7:22am UTC](https://forum.djangoproject.com/t/saving-2-models-within-a-single-form/9049/8 "2021-08-03T07:22:02Z")

</div>

Update: It worked BUT after adding one more new column it stop saving in the 2nd model. No error shown with : print(dd\_form.errors)

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [August 3, 2021, 12:45pm UTC](https://forum.djangoproject.com/t/saving-2-models-within-a-single-form/9049/9 "2021-08-03T12:45:41Z")

</div>

If the two forms have _any_ field names in common, you’ll want to use a [prefix with the forms](https://docs.djangoproject.com/en/3.2/ref/forms/api/#prefixes-for-forms).

If you edit your code blocks to be formatted properly (or repost them properly formatted), I can take a more detailed look.  
example:

````auto
# The line above this one is ```
def function():
    print("In function")
# The line after this one is ```

````

---

<div class="post-metadata">

**Author:** ![CalvinTheCat](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/calvinthecat/32/5343_2.png) [@CalvinTheCat](https://forum.djangoproject.com/u/CalvinTheCat)\
**Post date:** [August 20, 2021, 9:07am UTC](https://forum.djangoproject.com/t/saving-2-models-within-a-single-form/9049/10 "2021-08-20T09:07:44Z")

</div>

Sorry for the late reply. This issue is solved. Would u mind helping me with another issue i have posted a few hrs ago? Thank you very much
