Reputation: 393
I need to use data submitted by user in one view in another view. I don't want that data in the URL, and the data can not be extracted by calling the last object created, since many times it will not be that object.
My view for the index looks like this:
def index(request):
template_name = 'index.html'
if request.method == 'POST':
foo = request.POST['foo_text']
Foo.objects.get_or_create(foo=foo)
return redirect('/results/')
return render(request, template_name, {})
The template for this view is:
<html>
<title> Some Site </title>
<h1> Some site </h1>
<form action="/results/" method="POST" >
<input type="text" name="foo_text" id="id_foo_lookup" placeholder="Enter Your Foo">
{% csrf_token %}
</form>
The view to handle the data results is:
def results_view(request, foo):
template_name = 'movement_results.html'
results = Results.objects.filter(foo=foo)
return render(request, template_name, {'results' : results })
So as you can see the User will type some data, foo, into the index.html, which then gets or creates the object if it does not already exist in the database. From that the results view will return results based on the data submitted by the user previously. How do I get the foo data to the next view?
Upvotes: 0
Views: 2183
Reputation: 25539
I think you are confused of where the form should be submitted to. You wrote the code to accept POST
in index()
, so you definitely should POST
to index()
. Also you defined foo
as a parameter for results_view
, then when you redirect, you can't simply redirect to /results/
, but /results/<foo_id>
.
Although you've implemented most of the general flows correctly, there are many details I mentioned above you are missing, so please read more carefully about the django manual.
Here's my attempt to solve your confusion(untested):
index method:
def index(request):
template_name = 'index.html'
if request.method == 'POST':
foo_text = request.POST['foo_text']
foo, created = Foo.objects.get_or_create(foo=foo_text)
return redirect('/results/%s' % foo.id)
return render(request, template_name, {})
index.html:
<html>
<title> Some Site </title>
<h1> Some site </h1>
<form action="" method="POST" >
<input type="text" name="foo_text" id="id_foo_lookup" placeholder="Enter Your Foo">
{% csrf_token %}
</form>
results_view method:
from django.shortcuts import get_object_or_404
def results_view(request, foo_id):
template_name = 'movement_results.html'
result = get_object_or_404(Result, pk=foo_id)
return render(request, template_name, {'result' : result})
Upvotes: 1