I am new to Django and HTML and I am trying to display a list of data derived from a form on the HttpResponseRedirect page. I have been reading Django APIs but I am still unsure of how to use HttpResponse() and HttpResponseRedirect().
As of now I understand that response = HttpResponse() makes an HttpResponse object of and HttpResponseRedirect(‘results’) redirects the browser to a new html template page.
What I dont know is how to write results.html to display on my browser.
I need help on how to write the HTML page.
I also need help on how to pass a list of data to that html page.
I would also be ok with displaying the list on the same html page the form is in instead of loading a new page.
Current code:
def contact(request):
if request.method == 'POST': # If the form has been submitted...
form = ContactForm(request.POST) # A form bound to the POST data
chosen = []
if form.is_valid():
strt = time.time()
form = form.cleaned_data
parameters = organize(form)
print 'input organized'
chosen, companies = multiple(parameters)
end = time.time()
pp.pprint(companies)
print 'companies matching search filters: ' , len(companies)
print 'total time: ' , str(end-strt)
response = HttpResponse(chosen)
return HttpResponseRedirect('results') # Redirect after POST
I think what you want is Django’s render_to_response shortcut. The first argument is an html template to use, and the second is a dictionary of values to pass to that template.
At the top of your views.py file, include:
and modify your code to read:
Note that the second argument is a dictionary of values you’d like to pass to your template. The way I’ve written it, you’re passing 4 values (
chosen,companies,start,end) but you can include as many as you’d like.Then create a file named
results.htmlin your Templates directory (which is specified in theTEMPLATE_DIRSvariable in yoursettings.pyfile). It could look something like this:Django template syntax uses double curly braces
{{}}to display variables passed to the template.Note that this approach will not change the URL. If you need to do this, try looking at this.