Django-Pass data from html to python and wise versa

Index.html

<form class="grid" method="POST" action={% url 'result' %}>
   {% csrf_token %}
   <textarea name="name" /></textarea>
   <button type="submit"">Detect</button>
</form>
<label>{{name}}</label>

view.py

def result(request):
    name = request.POST['name']
    name=preprocessing(name)
    return render(
    request,
        "index.html",
        name=name
    )

urls.py

urlpatterns = [
    path("", views.homePage, name='result'),
]

i am making a website using django where i have to get data from html page in python file and after getting data i have to perform some preprocessing on data. and after that again return back to the same page with some new information when i press a button

The problem is with action attribute of HTML if you see it correctly, there should be "" in action, currently they are missing so it should be:

action="{% url 'result' %}"

Not:

action={% url 'result' %}

Note: You can also simply remove the action attribute as Django by default takes current page route.

Secondly, your view name is result in views.py and you define it as homePage in urls.py, kindly see it.

Also the view should pass some context dict so:

def result(request):
    name = request.POST['name']
    actual_name=preprocessing(name)
    return render(
    request,
        "index.html",
        {"name":actual_name}
    )

Edit:

Try this urls.py:

from django.urls import path
from mywebsite import views
urlpatterns = [
    path("", views.homePage, name='home-page'),
    path("", views.result, name="result"),
]

Try this result view:

def result(request):
    if request.method=="POST":
        namee = request.POST['name']
        namee2 =  test_data_preprocessing(namee)
        return render(
            request,
            "index.html",
           {"name":namee2}
        )
     return render(
            request,
            "index.html"
     )

Try this template:

<form class="grid" method="POST" action="{% url 'result' %}">
   {% csrf_token %}
   <textarea name="name" /></textarea>
   <button type="submit"">Detect</button>
</form>

{% if name %}
    <label>{{ name }}</label>
{% else %}
    <p> name is not coming as it is GET request.</p>
Back to Top