Changed default widget for TextField with choices to select box.

This commit is contained in:
Hasan Ramezani 2019-08-25 15:47:47 +02:00
parent ec1b14174f
commit 474145512a
No known key found for this signature in database
GPG Key ID: D0E2D7CE14B68267
2 changed files with 19 additions and 1 deletions

View File

@ -91,7 +91,8 @@ def get_field_kwargs(field_name, model_field):
if isinstance(model_field, models.SlugField):
kwargs['allow_unicode'] = model_field.allow_unicode
if isinstance(model_field, models.TextField) or (postgres_fields and isinstance(model_field, postgres_fields.JSONField)):
if isinstance(model_field, models.TextField) and not model_field.choices or \
(postgres_fields and isinstance(model_field, postgres_fields.JSONField)):
kwargs['style'] = {'base_template': 'textarea.html'}
if isinstance(model_field, models.AutoField) or not model_field.editable:

View File

@ -1,6 +1,7 @@
from unittest import mock
from django.conf.urls import url
from django.db import models
from django.test import TestCase, override_settings
from rest_framework.decorators import action
@ -8,6 +9,7 @@ from rest_framework.routers import SimpleRouter
from rest_framework.serializers import ModelSerializer
from rest_framework.utils import json
from rest_framework.utils.breadcrumbs import get_breadcrumbs
from rest_framework.utils.field_mapping import get_field_kwargs
from rest_framework.utils.formatting import lazy_format
from rest_framework.utils.urls import remove_query_param, replace_query_param
from rest_framework.views import APIView
@ -267,3 +269,18 @@ class LazyFormatTests(TestCase):
assert message.format.call_count == 1
str(formatted)
assert message.format.call_count == 1
class GetFieldKwargsTest(TestCase):
def test_get_text_field_kwargs(self):
# TextField without choices
f = models.TextField()
kwargs = get_field_kwargs('f', f)
assert 'style' in kwargs
assert 'choices' not in kwargs
# TextField with choices
f = models.TextField(choices=['ONE', 'TWO'])
kwargs = get_field_kwargs('f', f)
assert 'style' not in kwargs
assert 'choices' in kwargs