Home > Software design >  Dynamic URL routing from html form within action in Django
Dynamic URL routing from html form within action in Django

Time:09-06

I have a simple form which shall take a user input and directly send the user to a dynamic url using the input. Inputing "111" into the form shall send the user to http://127.0.0:8000/number_input=111

Somehow i can not get it done, since i do not know how to get direct variable value from the form to the view immediately. I can build it with 2 views but that looks somehow ugly and inconvenient.

Here is what i have so far:

The Form: (within index.html)

<form action={% url 'number_view'%} method="POST">
            {% csrf_token %}
            <p><input type="text" name="inp_number" placeholder="Insert Number"/></p>
            <p><input type="submit" value="Submit"/></p>            
        </form>

views.py:

def number_view(request):
    if request.method == 'POST':
        context = {'number': request.POST['inp_number']}
    return render(request, 'number.html', context)

urls.py

from . import views

urlpatterns = [  
    path('number_input=<int:number>/', views.number_view, name='number_view')
]

The dynamic part here (int:number) will make the code fail, since iam not sending a value from the form, right? But i only know how to send static values (i.e. action={% url 'my_view' 111 %}. How can i send direct dynamic values from the form itself (the value that the user inputs in the submit button)?

number.html

<h2>This page is for number {{ number }}</h2>

CodePudding user response:

You can redirect the user to the correct URL using redirect.

from django.shortcuts import redirect


def number_view(request):
    if request.method == 'POST':
        sent_number = request.POST['inp_number']
        return redirect('number_view', number=sent_number)

    return render(request, 'number.html', context)

For example, if you will handle the number only when it is posted:

from django.shortcuts import redirect


def number_view(request):
    number = None
    if request.method == 'POST':
        number = request.POST['inp_number']

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


urlpatterns = [  
    path('number_input/', number_view, name='number_view')
]
  • Related