Reputation: 35
Ok, so i have in my views.py these functions
def main(request):
if request.method == 'POST':
return newFunction(request)
return render(request,'user/main.html')
def newFunction(request):
num = request.POST["number"]
let = request.POST["letter"]
context = {'num':num,'let':let}
return render(request,'user/test.html',{'c':context})
And that main.html looks like this
{%extends 'base/base.html'%}
{%block title%}Main{%endblock%}
{%block content%}
<form method="post">
{%csrf_token%}
<input type="text" name="number">
<input type="text" name="letter">
<button type="submit">Save</button>
</form>
{%endblock%}
The urls.py
path('index/',main,name='main'),
path('test/',newFunction,name='test'),
As you can see, i enter the main.html page and a form appears, asking me for a number and a letter. I enter these 2 inputs and when clicking the submit, it redirects me to another html and show me the letter and number. The problem is that the url still shows user/index.html, not user/test.html
How can i do this? i want to basically click the submit and send all the values to another template but changing the url in the process.
Upvotes: 0
Views: 970
Reputation: 2956
You can use ajax for do that. You can use form either, but ajax is more appropriate for just passing data to view.
Just sending ajax request with some data, and send it to your target view.
$.ajax({
type: 'POST',
url: "{% url 'test' %}",
data: {
"csrfmiddlewaretoken": "{{ csrf_token }}",
"num": 'number',
"let": 'letter'
},
dataType: 'json',
success: function(e) {
// success after receive response
}
});
Of course you can send it with form
. Just add your target url in action
.
<!-- add your target url in action -->
<form method="post" action="{% url 'test' %}">
{%csrf_token%}
<input type="text" name="number">
<input type="text" name="letter">
<button type="submit">Save</button>
</form>
Upvotes: 2
Reputation: 1745
This can be handled on the frontend, using the action
attribute within the opening <form>
tag whose value should be the URL you want the form's data to be POST
'd to on submit. Your opening <form>
tag can be changed to the following:
<form method="post" action="/user/test.html">
Read: https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Sending_and_retrieving_form_data
Upvotes: 0