PA_Commons
PA_Commons

Reputation: 269

Django view not passing IP address data from form

Trying to do something simple here where I pass an IP address from a form to another view. Previously I had success following beginner tutorials. If someone could point me back to what I'm missing that would be a huge help.

model:

class GenericIP(models.Model):
    name = models.CharField(max_length=50)
    genericip = models.GenericIPAddressField()

    def __str__(self):
        return self.name 

form:

class IpForm(forms.Form):
    gateway = ModelChoiceField(queryset=GenericIP.objects.order_by('name').values_list('genericip', flat=True).distinct())

views:

def TestCreate(request):
    if request.method == 'GET':
        form1 = IpForm()
        return render(request, 'create_test.html', {'form1' : form1} )
    else:
        if request.method == 'POST':
            form1 = IpForm()
            if form1.is_valid():
                genericip = form1.cleaned_data
                genericip.save()
            return render(request, 'create_test.html', {'genericip' : genericip} )

def RunTest(request, genericip=""):
    if request.method == 'POST':
        Server = genericip
    return HttpResponse(Server)

URLS:

urlpatterns = [
    path('', views.TestCreate, name='create_test'),
    path('run_test', views.RunTest, name='run_test',),
    ]

template:

{% block content %}
<form action="{% url 'run_test' %}"method='post'>
    {% csrf_token %}
    {{ form1 }}
    <input type='submit' class="btn btn-success" value='Run Test'>
</form>
{% endblock %}

So what's happening is when I hit the button to run the test, I don't get anything for the httpresponse. The post data for the TestCreate view does show variable "genericip" and input "192.168.100.100" but that data is not posting correctly to the runtest view.

Upvotes: 0

Views: 190

Answers (2)

Ajay Kumar
Ajay Kumar

Reputation: 1655

In the RunTest function, you are getting the genericip value as a function argument.But in your scenario you are sending the genericip vaule in the form of form submit. So you should try some thing like this,

def RunTest(request):
    if request.method == 'POST':
        ip = request.POST.get('gateway') # Some thing with form field name
        Server = ip
    return HttpResponse(Server)

Hope this helps you, if anything please let me know.

Upvotes: 2

YPCrumble
YPCrumble

Reputation: 28682

You aren't adding the POST data to the form instance in the post request - you're just instantiating an empty IpForm instance.

Try something like this in the appropriate section of your code:

if request.method == 'POST':
    form1 = IpForm(data=request.POST)

Upvotes: 2

Related Questions