0

Basically I have this form right here

<form method="POST" action=".">
   <input type="text" name="fcal" value="{{F}}" />
<p>
   <input type="submit" name="fibo" value="Fibonacci" />
</p>
</form>

I would like the user to input a number and after that this number to be calculated and printed in a Fibonacci sequence.

This is my Fibonacci function

def fibo(n):
    if n == 0:
       return 0
    elif n == 1:
       return 1
    else:
       result = fibo(n - 1) + fibo(n - 2)
       return result

I believe my problem is coming from the views.py file because I am not sure how to create the result to be rendered back.

from django.template import Context, loader, RequestContext
from django.shortcuts import render_to_response, get_object_or_404
from django.forms import ModelForm
from django.http import HttpResponse, Http404, HttpResponseRedirect, HttpResponseNotFound
import fibonacci


def fibocal(request):
    if request.method == 'POST':
       fb = request.POST['fcal']
       cal = fibonacci.fibo(fb)
       return render_to_response('fibb/fibb.html', context_instance=RequestContext(request, cal))
    else:
       print('Wrond input type')

I would highly appreciate if someone can at least explain how to get the result from a function and print it out on the same page.

1 Answer 1

1

your html file

    <form method="POST" action=".">
       <input type="text" name="fcal" value="{{F}}" />
    <p>
       <input type="submit" name="fibo" value="Fibonacci" />
    </p>
    </form>

{% if cal %}
      Your Fibonacci answer is {{cal}} 
{% endif %}

Your view:

def fibocal(request):
    if request.method == 'POST':
       fb = request.POST['fcal']
       cal = fibonacci.fibo(fb)
       return render(request, 'fibb/fibb.html', {'cal': cal})
    else:
       return render(request, 'fibb/fibb.html', {})

This will do the trick

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your response I've edit my code but right now the error which I have is: The view fibb.views.fibb didn't return an HttpResponse object. It returned None instead.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.