[Fixed]-Django form based view GET response

1๐Ÿ‘

โœ…

You need to access form data in like this:

data = form.cleaned_data['data']

So your view has to look like:

def index(request):
    if request.method == 'GET':
        form = CurrencyConverterForm(request.GET)
        if form.is_valid():
            base_currency = form.cleaned_data['base_currency']
            counter_currency = form.cleaned_data['counter_currency']
            base_amount = form.cleaned_data['base_amount']

        counter_amount = get_conversion_amount(base_currency, counter_currency, datetime.now(), base_amount)

        response = HttpResponseRedirect('/')
        response['base_currency'] = base_currency
        response['counter_currency'] = counter_currency
        response['base_amount'] = base_amount

        return response
else:
    form = CurrencyConverterForm()

context = {'form': form}

return render(request, '../templates/client/index.html', context)
๐Ÿ‘คpythad

0๐Ÿ‘

I have been able to solve it.

I actually needed a lot less code then I expected.

def index(request):
    counter_amount = ""
    if request.method == 'GET':
        form = CurrencyConverterForm(request.GET)
        if form.is_valid():
            form_base_currency = form.cleaned_data['form_base_currency']
            form_counter_currency = form.cleaned_data['form_counter_currency']
            form_base_amount = form.cleaned_data['form_base_amount']

            # Calculate the counter_amount
            counter_amount = get_conversion_amount(form_base_currency, form_counter_currency, datetime.now(),
                                                   form_base_amount)
            # Retrieve the counter amount from the dict
            counter_amount = counter_amount['GetConversionAmountResult']
            # Maximize the number of decimals to 4
            if counter_amount.as_tuple().exponent < -4:
                counter_amount = "%.4f" % counter_amount

    else:
        form = CurrencyConverterForm()

    context = {
        'form': form,
        'counter_amount': counter_amount
    }

    return render(request, '../templates/client/index.html', context)
๐Ÿ‘คJohan Vergeer

Leave a comment