From 4f3480d9f0717c4a16ccdc55576bb17c2bd662c0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Padilla?= Date: Mon, 27 Mar 2017 08:05:42 -0700 Subject: [PATCH] Fix unique validator for ChoiceField --- rest_framework/utils/field_mapping.py | 3 --- tests/test_serializer.py | 35 +++++++++++++++++++++++++++ 2 files changed, 35 insertions(+), 3 deletions(-) diff --git a/rest_framework/utils/field_mapping.py b/rest_framework/utils/field_mapping.py index 29005f6b7..bf42867f9 100644 --- a/rest_framework/utils/field_mapping.py +++ b/rest_framework/utils/field_mapping.py @@ -123,10 +123,7 @@ def get_field_kwargs(field_name, model_field): kwargs['allow_folders'] = model_field.allow_folders if model_field.choices: - # If this model field contains choices, then return early. - # Further keyword arguments are not valid. kwargs['choices'] = model_field.choices - return kwargs # Our decimal validation is handled in the field code, not validator code. # (In Django 1.9+ this differs from previous style) diff --git a/tests/test_serializer.py b/tests/test_serializer.py index f76cec9c3..6aaec96c7 100644 --- a/tests/test_serializer.py +++ b/tests/test_serializer.py @@ -9,6 +9,7 @@ from collections import Mapping import pytest from django.db import models +from django.test import TestCase from rest_framework import fields, relations, serializers from rest_framework.compat import unicode_repr @@ -519,3 +520,37 @@ class TestDeclaredFieldInheritance: assert len(Parent().get_fields()) == 2 assert len(Child().get_fields()) == 2 assert len(Grandchild().get_fields()) == 2 + + +CHOICES = ( + ('choice1', 'choice 1'), + ('choice2', 'choice 1'), +) + + +class Poll(models.Model): + form_name = models.CharField( + 'name', max_length=254, unique=True, choices=CHOICES + ) + + +class Test5004(TestCase): + def test_unique_choice_field(self): + Poll.objects.create(form_name='choice1') + + class PollSerializer(serializers.ModelSerializer): + class Meta: + model = Poll + fields = '__all__' + + serializer = PollSerializer(data={'form_name': 'choice1'}) + + with self.assertRaises(serializers.ValidationError) as excinfo: + serializer.is_valid(raise_exception=True) + + assert excinfo.exception.get_full_details() == { + 'form_name': [{ + 'message': 'poll with this name already exists.', + 'code': 'unique' + }] + }