Django - Add two names - Couldn't print results

Viewed 19

I'm new to Django.

Trying to build an app that adds two names. Pretty Basic.

Built a page that collects the names but not printing the final result.

Here is my code:

urls.py - inside the app

urlpatterns = [
    path('',views.home, name='home'),
    path('add',views.addname,name='add')
]

views.py

from django.shortcuts import render
from django.http import HttpResponse

def home(request):
    return render(request,'input.html')

def addname(request):
    val1 = (request.POST['fname'])
    val2 = (request.POST['lname'])
    res = 'Hi' + val1 +val2

    return render(request, 'resultprint.html',{'resultprint':res})

templates/input.html

{% block content %}
<h1>Hello!</h1>

<form action='addname' method='post'>

    {% csrf_token %}
    Enter 1st name : <input type='text' name='fname'><br>
    Enter 2nd name : <input type='text' name='lname'><br>
    <input type='submit'>

</form>    


{%endblock%}

templates/resultprint.html

{% block content %}

Result: {{resultprint}}

{%endblock%}

Below are the screenshots: screenshot 2

enter image description here

Couldn't really find where is the mistake happening.

I added the templates and app in the Settings file.

1 Answers

You have to set the same url in your urls.py :

urlpatterns = [
    path('', views.home, name='home'),
    path('addname', views.addname, name='addname')
]

But you can use directly the name of the url in your html file like that :

{% block content %}
<h1>Hello!</h1>

<form action='{% url 'addname' %}' method='post'>

    {% csrf_token %}
    Enter 1st name : <input type='text' name='fname'><br>
    Enter 2nd name : <input type='text' name='lname'><br>
    <input type='submit'>

</form>    


{%endblock%}
Related