display variable from form on html page

I am attempting to create a router config generator using django forms. The idea is that the form takes input / choices and these are then displayed on a page called config_page.html.

Where I am getting stuck is being able to create a new variable based on input and displaying this in the config_page.html.

So for example lets say from the choices for ‘WAN_SubnetMask’ ‘30’ is selected and some numbers are entered for ‘WAN_Subnet’, I want to take the integers entered for ‘WAN_Subnet’, perform some very basic math e.g. add 2 and then create a new variable called ‘WAN_IP’.

I can display objects from my database in my config_page.html however the variable ‘WAN_IP’ does not display at all.

Here is what I have come up with so far, I have tried adding the logic to create the ‘WAN_IP’ variable in both forms and views.

forms.py

from django import forms
from .models import CPEconfig

Router = [
    ('2901', 'Cisco 2901'),
    ('1941', 'Cisco 1941'),

WAN_SubnetMask = [
    ('30', '30'),
    ('29', '29'),
    ]

LAN_SubnetMask = [
    ('30', '30'),
    ('29', '29'),
    ]    

class ConfigForm(forms.ModelForm):
    Router = forms.CharField(label='Select Router', widget=forms.Select(choices=Router))
    WAN_Subnet = forms.GenericIPAddressField()
    WAN_SubnetMask = forms.CharField(label='WAN Subnet Mask', widget=forms.Select(choices=WAN_SubnetMask))
    LAN_SubnetMask = forms.CharField(label='LAN Subnet Mask', widget=forms.Select(choices=LAN_SubnetMask))
    
    class Meta:
        model = CPEconfig
        fields = ('WAN_Subnet', 'WAN_SubnetMask', 'LAN_Subnet', 'LAN_SubnetMask', 'Router')

    def clean(self):
        cleaned_data = super().clean()
        WAN_SubnetMask = cleaned_data.get('WAN_SubnetMask')
        if (WAN_SubnetMask) == '30':
            WAN_IP = WAN_Subnet + 2
models.py

from django.db import models

# Create your models here.
class CPEconfig(models.Model):
    WAN_Subnet = models.CharField(max_length=50, null=True)
    LAN_Subnet = models.CharField(max_length=50, null=True)
    WAN_SubnetMask = models.IntegerField(null=True)
    LAN_SubnetMask = models.IntegerField(null=True)
    Router = models.CharField(max_length=50, null=True)

    def __str__(self):
        return str(self.Router)
views.py

from django.shortcuts import render
from django.http import HttpResponse
from CPEconfigs_app.models import CPEconfig
from .forms import ConfigForm

# Create your views here.
def CPEgen(request):
    if request.method == 'POST':
        form = ConfigForm(request.POST)
        if form.is_valid():
            WAN_IP = form.cleaned_data['WAN_SubnetMask']
            form.save()
                            
    else:
        form = DIAForm()
    return render(request, 'CPEgen.html', {'DIAForm': form})

def config_page(request):
    display_config = CPEconfig.objects.last

    return render(request, 'config_page.html', {'display_config': display_config})
config_page.html

{% extends 'base.html' %}

{% block title %}
    <title>Config_page</title>
{% endblock title %}

{% block content %}
    <div class="container">
        <h1>{{ display_config.SubnetMask }} {{ display_config.Router }} {{ WAN_IP }}</h1>

    </div>

     
{% endblock content %}

<h2>{{ data }}</h2>

Hi!

I think the problem is WAN_IP is assigned a value here but it’s not saved with the form. (It’s not defined in the model)

One way this could be done is by calculating the WAN_IP like a derived attribute also called calculated field.

class CPEconfig(models.Model):
    WAN_Subnet = models.CharField(max_length=50, null=True)
    LAN_Subnet = models.CharField(max_length=50, null=True)
    WAN_SubnetMask = models.IntegerField(null=True)
    LAN_SubnetMask = models.IntegerField(null=True)
    Router = models.CharField(max_length=50, null=True)

    def __str__(self):
        return str(self.Router)

   def WAN_IP(self):
        return self.WAN_SubnetMask + 2

Then in your template you can call it like this:
{{ display_config.WAN_IP }}

1 Like

Hi, and thanks for reply!

So I added this to models.py:

def WAN_IP(self):
return self.WAN_SubnetMask + 2

and attempted to call it with {{ display_config.WAN_IP }} in my template but it still does not display.

I then tried defining WAN_IP in my model as below but still no luck.

WAN_IP = models.IntegerField(null=True)

Sorry if I missed something, I am new to Django and thanks once again.

If you do it this way take note WAN_SubnetMask must have a value.

One thing I noted now is that you’re calling last withouth the ().
I think what you want is to assign the last CPEconfig object to the display_config variable.

def config_page(request):
+    display_config = CPEconfig.objects.last()
-    display_config = CPEconfig.objects.last

Have you updated the form? Run the migrations after adding the field?
Check those steps which are frequently forgotten (at least to me :sweat_smile:)

I’ve not added WAN IP to forms as it’s supposed to be a variable that’s created based on what the user chooses for WAN_SubnetMask rather than a field for the user to fill in directly.

When you mentioned a calculated field earlier is that something that needs to be created in forms for WAN IP rather than a standard field?

The only change I made to forms was removing:

def clean(self):
cleaned_data = super().clean()
WAN_SubnetMask = cleaned_data.get(‘WAN_SubnetMask’)
if (WAN_SubnetMask) == ‘30’:
WAN_IP = WAN_Subnet + 2

As clean was being done on views it seemed like this section was redundant. Other than that my forms.py is the same as it was to start with.

I have run migrations after adding WAN_IP to models and am also calling CPEconfig.objects.last() with brackets now.

One other thing to note is that now that WAN_IP is in models, I am not seeing an entry for it after the form has been submitted when I view my database entries in the admin section. Again I am assuming that this section in views is supposed to be creating an entry for WAN_IP:

if form.is_valid():
WAN_IP = form.cleaned_data[‘WAN_SubnetMask’]
form.save()

I’m not sure I understand if you’re using a model field or a calculated field.

What I meant is that you can store WAN_IP in the model or you can calculate it based on another value, not both.

Not really. This is just a normal model method that behaves like a field.

Maybe you need to update the ModelAdmin to include that field?

Just wanted to let you l got this working and say thanks at the same time.

I’d done something stupid with the formatting of the functions and had them set to the left rather than indented. It didn’t produce an error so I didn’t realise at the time, once it was indented it started working.

Good to know and nevermind, it happens to everyone. :sweat_smile: