I'm trying to get a value from correct_answer key in a JSON field inside a model that is previously fetched from an external API. That value is used in a conditional to redirect (right answer) or render a new question (wrong answer).
When I tried to access the value as a dictionary from a mocked version of the model my test complains with a 'DefferedAttribute' object is not subscriptable. We could say that data isn't fetched from the external API but I checked that the mocked model was working.
This is my code:
from django.shortcuts import redirect, render, HttpResponse
from django.template import loader
from .forms import QuestionForm, QuestionLevelForm
from urllib.request import urlopen, URLError
from .models import Log
def process_question(request):
form={};
if 'level' in request.POST:
url = 'http://opentb.com/api.php?amount=1&category=9&difficulty='+request.POST['level']+'&type="multiple"'
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]
form = QuestionForm(question)
Log.question = question #How to test this works?
Log.save(update_fields=['question'])
return render(request, "log/question.html", {"question": question, "form": form})
elif 'answer' in request.POST:
if request.POST["correct_answer"] == Log.question['correct_answer']: #This is the conditional I need
return redirect('/log/reward')
else:
notification = "Wrong answer"
level = QuestionLevelForm
return render(request, "log/question.html", {"form": level, "notification": notification})
else:
form = QuestionLevelForm();
return render(request, "log/question.html", {"form": form})
Here's my model:
from django.db import models
class Log(models.Model):
recipe_ingredients = models.JSONField(null=True)
recipe_area = models.JSONField(null=True)
recipe_categories = models.JSONField(null=True)
activities = models.JSONField(null=True)
question = models.JSONField(default=dict)
class Meta:
abstract = True
def save(self, *args, **kwargs):
self.__class__.objects.exclude(id=self.id).delete()
super(Log, self).save(*args, **kwargs)
@classmethod
def load(cls):
try:
return cls.objects.get()
except cls.DoesNotExist:
return cls()
After several tries with querying the field I found this Stackoverflow question that made more sense to me. However, it didn't work in this case.
Can anybody point out what I'm missing/doing wrong please?