I'm using Django 2.2, Python 3.7, the Django rest framework, and pytest. I want to write a unit test to see if my serializer can create my model. My test looks like this ...
@pytest.mark.django_db
def test_coop_create(self):
""" Test coop serizlizer model """
state = StateFactory()
serializer_data = {
"name": "Test 8899",
"types": [
{"name": "Library"}
],
"address": {
"formatted": "222 W. Merchandise Mart Plaza, Suite 1212",
"locality": {
"name": "Chicago",
"postal_code": "60654",
"state_id": state.id
}
},
"enabled": "true",
"phone": "7739441426",
"email": "myemail",
"web_site": "http://www.1871.com/"
}
serializer = CoopSerializer(data=serializer_data)
serializer.is_valid()
print(serializer.errors())
assert serializer.is_valid(), serializer.errors()
result = serializer.save()
print(result)
However, "serializer.errors()" is producing the output
TypeError: 'ReturnDict' object is not callable
I'm not clear on why or how to debug further. The code for my serializer is
class CoopSerializer(serializers.ModelSerializer):
types = CoopTypeSerializer(many=True)
address = AddressTypeField()
class Meta:
model = Coop
fields = ['id', 'name', 'types', 'address', 'phone', 'enabled', 'email', 'web_site']
extra_kwargs = {
'phone': {
'required': False,
'allow_blank': True
}
}
def to_representation(self, instance):
rep = super().to_representation(instance)
rep['types'] = CoopTypeSerializer(instance.types.all(), many=True).data
rep['address'] = AddressSerializer(instance.address).data
return rep
def create(self, validated_data):
#"""
#Create and return a new `Snippet` instance, given the validated data.
#"""
coop_types = validated_data.pop('types', {})
instance = super().create(validated_data)
for item in coop_types:
coop_type, _ = CoopType.objects.get_or_create(name=item['name']) #**item)
instance.types.add(coop_type)
return instance
and the underlying model code is ...
class Coop(models.Model):
objects = CoopManager()
name = models.CharField(max_length=250, null=False)
types = models.ManyToManyField(CoopType)
address = AddressField(on_delete=models.CASCADE)
enabled = models.BooleanField(default=True, null=False)
phone = PhoneNumberField(null=True)
email = models.EmailField(null=True)
web_site = models.TextField()
Here's a GitHub link if you really want to get crazy -- https://github.com/chicommons/maps/tree/master/web.
It should be serializer.errors
instead of serializer.errors()
.errors
is a property
, not a method :)