user185887
user185887

Reputation: 713

Keeping url same while updating contents of page after form submission using Django

I built an html form using the <form> tag and not using built in Django forms. The form asks for name and age. What I want to do is that after the user fills the form, the url of the page is kept same, while the contents of the page are changed to display name and age. How can I do that?

<html>
<head>
	<title>Form</title>
</head>
<body>

	<form method="post" action="aftersubmit">
		{% csrf_token %}
		<input placeholder="yourname" name="name">
		<br>
		<input placeholder="your age" name="age">
		<br>
		<input type="submit" value="Submit">
	</form>
</body>
</html>

from django.shortcuts import render,redirect
# Create your views here.

def formpage(request):
    return render(request,'formhtml.html')

def aftersubmit(request):
    name = request.POST['name']
    age = request.POST['age']
    dictionary = {
    "name":name,
    "age":age
    }
    print(dictionary)
    return redirect('formpage')

My current code keeps the url same but does not modify the contents of the page.

Upvotes: 0

Views: 30

Answers (2)

bb4L
bb4L

Reputation: 919

you can achieve the behavior in one view:

check for the request type

if it's post read age and name as in your aftersubmit view.

def formpage(request):
    if request.method == 'POST':
        name = request.POST['name']
        age = request.POST['age']
        return render(request, 'formhtml.html', {'name': name, 'age':age}) # you could also swap the template if you want
    else:
        return render(request,'formhtml.html')

and render the view with context containing name and age

in the template check if the age and/or name is present and check that the action is pointing to the same view

{% if name %}
{{name}}  {{age}}
{% else %}
your form you already have
{% endif %}

example from the documentation: https://docs.djangoproject.com/en/3.0/topics/forms/

Upvotes: 1

Ahmed I. Elsayed
Ahmed I. Elsayed

Reputation: 2130

Form action expects the url, so {% url 'aftersubmit' %} should work. HOWEVER, forms that don't trigger refresh SHOULD HAVE NEITHER ACTION ATTRIBUTE NOR SUBMIT BUTTON as the submit event is the event responsible for the refresh. What you're looking for is called AJAX and you can find your answer here, or use Axios library to call your view. Using ajax puts some work on the Front-End, As now you have to manually change the data on the Front-End compared to what we had before "The refresh".

Upvotes: 0

Related Questions