Talha Chafekar
Talha Chafekar

Reputation: 93

How to route to a url based on data entered in Django form?

At first , I would like to take an integer input from user . After getting the input , I would like to go to the url based on what the user has entered . However , I am not able to implement it . Here's my urls.py file:

urls.py

urlpatterns = [
    path('',views.page1),
    re_path(r'^form/(?P<data>[1-4]{1})',views.page2),
]

Here's my views.py file:

views.py

from django.shortcuts import render
from .forms import CustomForm1
from django.http import HttpResponse
import requests
# Create your views here.
def page1(request):
    if request.method == 'POST':
        form = CutsomForm1(request.POST)
        if form.is_valid():
            data = form.cleaned_data['data']
    else:
        form = CustomForm1
        data = 0
    return render(request,'homepage/base.html',{'form':form,'data':data})

This is my forms.py file:

forms.py

from django import forms

class CustomForm1(forms.Form):
    data = forms.IntegerField(label='data',required=True)

And here's the HTMl:

HTML

<form method="POST" action="form/{{ data }}">
            {% csrf_token %}
            {{ form.as_p }}
            <ul class="actions">
                <li><input type="submit" value="Send Message" class="primary" /></li>
                <li><input type="reset" value="Clear" /></li>
            </ul>
        </form>

Initially , when the form is loaded , my data variable has value 0 , but I want to it get the value which is entered by user , hence , I can then route to the desired url as per the updated data variable which is passed as context .

For example , in the input field ,if the user enters 1 , I want it to go to form/1 but i feel that the django templating is static and is not updateable once passed.Any other way I can implement it?

Upvotes: 0

Views: 3136

Answers (1)

Moha369
Moha369

Reputation: 834

In views.py :

from django.urls import reverse
from django.urls import redirect

def page1(request):
    if request.method == 'POST':
        form = CustomForm1(request.POST)
        if form.is_valid():
            data = form.cleaned_data['data']
            return redirect(reverse('form_url', kwargs = {'data' : data}))
    else:
        form = CustomForm1
        data = 0
    return render(request,'homepage/base.html',{'form':form,'data':data})

urls.py:

urlpatterns = [
    path('',views.page1),
    re_path(r'^form/(?P<data>[1-4]{1})',views.page2, name = 'form_url')
]

Basically I cleaned 1 from the form and used reverse to create the url and I redirected to it. Read about reverse : https://docs.djangoproject.com/en/dev/ref/urlresolvers/#reverse

[EDIT] as @mihai mentioned in the comments, remove the action="form/{{ data }}" if you want this answer to work.

Upvotes: 1

Related Questions