How to render a dictionary passed as Django Form Class parameter

16 Views Asked by At

I've got a template that renders two predefined forms depending on two different POST requests handled by a single view method to keep just one URL end point for the whole interaction. Form one doesn't take any parameters but form two does take an external API response a one. How can render the dictionary contents of that response as choice fields in form two class?

view.py

from django.shortcuts import render, HttpResponse
from django.template import loader
from .forms import QuestionForm, QuestionLevelForm
from urllib import urlopen

def process_question(request):
    if 'level' in request.POST:
        url = 'http://opentdb.com/api.php?amount=1&category=9&type="multiple"&level='
        url += request.POST["level"]
        try:
            response = urlopen(url)
        except URLError as e:
            if hasattr(e, 'reason'):
                HttpResponse('Reaching server failed: ', e.reason)
            elif hasattr(e, 'code'):
                HttpResponse('Couldn\'t fufill request', e.code)
        else:
            question = response["results"][0]
            # API response passed to Form class instance as parameter
            form = QuestionForm(question)
            return render(request, "log/question.html", {"question": question, "form": form})
    elif 'answer' in request.POST:
        return HttpResponse('NOT IMPLEMENTED: Check answer')
    else: 
        form = QuestionLevelForm();

    return render(request, "log/question.html", {"form": form})

forms.py

from django import forms
from django.forms import widgets

class QuestionLevelForm(forms.Form):
    choices = (('', '---Please choose a level---'), ('easy', 'Easy'), ('medium', 'Medium'), ('hard', 'Hard'))
    label = forms.CharField(label="Choose your question level")
    select = forms.CharField(widget=forms.Select(choices=choices))
    
class QuestionForm(forms.Form):
    # Gets question dictionary from view
    # Question text
    label = forms.CharField(widgets=forms.label)
    # How to render multiple choice answer from parameter?

template/log/question.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Question</title>
  </head>
  <body>
    { % if notification % }
    <h3>{{notification}}</h3>
    { % endif % }
    <form action="" method="post">
      { % csrf_token % }
      {{ form }} 
      { % if question % }
      <input type="submit" name="answer" value="answer">
      { % else % }
      <input type="submit" name="level" value="level">
      { % endif % }
    </form>
  </body>
</html>
0

There are 0 best solutions below