Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Create dynamic action URL form in Django python

whenever I submit the form it takes me to the testformresult page like https://www.studnentdetail.com/student/testformresult but What I want is, when someone enters the name of the student in the form.html page then data of that student is fetched from the mysql database and displayed on another page something like https://www.studentdetail.com/student/<student_name>. Also I want to know how like many railway site when we search for particular train like 10029 then in the next page it shows url something like https://www.train/10029-running-status.

form.html

<form method="POST" action="{% url 'testformresult' %}">

    <label for="fname">First Name</label>
    <input type="text" id="fname" name="firstname" placeholder="Your name..">

    <input type="submit" value="Submit">
  </form>

views.py

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

def testform(request):
    return render(request, 'testform.html')

def testformr(request):
    fname = request.POST.get('firstname')
    return render(request, 'testformresult.html')

urls.py

path('testform', views.testform, name='testform'),
path('student/testformresult/<slug:student>', views.testformresult, name='testformresult'),

>Solution :

you can try it with a redirect:
(and think about using a CSRF Token and enable CsrfViewMiddleware … see django docs https://docs.djangoproject.com/en/4.0/ref/csrf/ !!)

form.html

<form method="POST">

    {% csrf_token %}    

    <label for="fname">First Name</label>
    <input type="text" id="fname" name="firstname" placeholder="Your name..">

    <input type="submit" value="Submit">
  </form>

views.py

def testform(request):
    if request.method == 'POST':
       ....
       fname = request.POST.get('firstname')
       return redirect('testformresult', student=fname)

    return render(request, 'testform.html')

urls.py

path('testform', views.testform, name='testform'),
path('student/testformresult/<slug:student>', views.testformresult, name='testformresult'),
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading