getting keyError: 'request' i am getting this error when i am to create an evaluation test i am newbie to django rest framework can somebody help me why i am getting this error

2,149 views
Skip to first unread message

zohaib younis

unread,
Apr 8, 2019, 4:27:53 AM4/8/19
to Django REST framework
def validate(self, data, *args, **kwargs):
questions = self.context['request'].data.get("questions")
if not questions:
raise serializers.ValidationError("questions are required")
if self.context["request"].method == "POST":
self.questions = QuestionSerializer(data=questions, many=True)
self.questions.is_valid(raise_exception=True)
elif self.context["request"].method == "PUT":
self.questions = questions
self.new_questions = self.context["request"].data.get(
"new_questions")
if self.new_questions:
self.new_questions = QuestionSerializer(
data=self.new_questions, many=True)
self.new_questions.is_valid(raise_exception=True)
return data

def create(self, data):
evaluation_test = EvaluationTest()
evaluation_test.category = data['category']
evaluation_test.admin = data['admin']
evaluation_test.title = data['title']
evaluation_test.type = data['type']
evaluation_test.save()

for question in data['questions']:
question.evaluationtest = evaluation_test
question.save()
return evaluation_test

def update(self, instance, validated_data):
instance.title = validated_data.get["title", instance.title]
instance.type = validated_data.get["type", instance.type]
instance.category = validated_data.get["category", instance.category]
instance.admin = validated_data.get["admin", instance.admin]

for question in self.questions:
q = QuestionSerializer(instance=question["id"], data=question)
q.is_valid(raise_exception=True)
q.save()

if self.new_questions:
new_questions = self.new_questions.save()
for question in new_questions:
question.save()
return instance

Arbaz Hundekar

unread,
Apr 8, 2019, 9:01:01 AM4/8/19
to django-res...@googlegroups.com
while instantiating your serializer do like this ser = Serializer(context={"request": request})

--
You received this message because you are subscribed to the Google Groups "Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-rest-fram...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


--
Warm Regards,

Arbaz

zohaib younis

unread,
Apr 8, 2019, 9:05:04 AM4/8/19
to django-res...@googlegroups.com
arbaz thanks for your guidance i have resolved that issue now when i try to create a test it is giving me an error 
for question in data["questions"]:
keyError :'questions'
can you help me with that problem thanks 

Arbaz Hundekar

unread,
Apr 8, 2019, 9:08:05 AM4/8/19
to django-res...@googlegroups.com
try this
questions = self.context['request'].data.get("questions",None)

If questions is not in request.data it will be set to None. It will work with your not condition as well.

zohaib younis

unread,
Apr 8, 2019, 9:10:50 AM4/8/19
to django-res...@googlegroups.com
from rest_framework import serializers
from .models import EvaluationTest, Question, Choice, GradeEvaluationText, Category
from users.models import User


class StringSerializer(serializers.StringRelatedField):
def to_internal_value(self, value):
return value


class ChoiceSerializer(serializers.ModelSerializer):
class Meta:
model = Choice
fields = '__all__'


class QuestionSerializer(serializers.ModelSerializer):
choices = ChoiceSerializer(many=True)
answer_text = serializers.CharField(
max_length=50, required=True, write_only=True)

class Meta:
model = Question
fields = ('id', 'choices', 'question',
'order', 'answer_text', 'answer')
read_only_fields = ('answer', )

def validate(self, attrs):
attrs = super().validate(attrs)
if not any(map(lambda x: x['title'] == attrs["answer_text"], attrs["choices"])):
raise serializers.ValidationError("Answer must match the choices")

self.answer_text = attrs["answer_text"]
del attrs["answer_text"]
return attrs

def create(self, validated_data):
choices = validated_data.pop("choices")
question = super().create(validated_data)
for choice_data in choices:
choice = Choice.objects.create(title=choice_data["title"])
question.choices.add(choice)
if choice_data["title"] == self.answer_text:
question.answer = choice
question.save()
return question

def update(self, instance, validated_data):
choices = validated_data.pop["choices"]
instance = super().update(instance, validated_data)
choices = ChoiceSerializer(data=choices, many=True)
choices.is_valid(raise_exception=True)
choices = choices.save()

old_ids = list(instance.choices.values_list("id", flat=True))
for choice in choices:
instance.choices.add(choice)
if self.answer_text == choice.title:
instance.answer = choice
Choice.objects.filter(id__in=old_ids).delete()

return instance


class CategorySerializer(serializers.ModelSerializer):
class Meta:
model = Category
fields = '__all__'


class EvaluationTestSerializer(serializers.ModelSerializer):
questions = serializers.SerializerMethodField()

class Meta:
model = EvaluationTest
fields = '__all__'

def get_questions(self, obj):
return QuestionSerializer(obj.questions.all(), many=True).data

# def by_category(category_id):
# tests = EvaluationTest.objects.filter(category_id=category_id)
# items = EvaluationTestSerializer(tests, many=True).data
# return items

def validate(self, data, *args, **kwargs):
questions = self.context["request"].data.get("questions",None)
instance.title = validated_data.get("title", instance.title)
instance.type = validated_data.get("type", instance.type)
instance.category = validated_data.get("category", instance.category)
instance.admin = validated_data.get("admin", instance.admin)

for question in self.questions:
q = QuestionSerializer(instance=question["id"], data=question)
q.is_valid(raise_exception=True)
q.save()

if self.new_questions:
new_questions = self.new_questions.save()
for question in new_questions:
question.save()
return instance

zohaib younis

unread,
Apr 8, 2019, 9:11:40 AM4/8/19
to django-res...@googlegroups.com
arbaz bro i am still getting the same error

Gonzalo Amadio

unread,
Apr 10, 2019, 1:04:31 AM4/10/19
to Django REST framework
Key error, means that key 'question' it's not in data.

Put a debugger and inspect what's in data.
Reply all
Reply to author
Forward
0 new messages