From 101aff6c43f6fa96174683e050988428143d1040 Mon Sep 17 00:00:00 2001 From: Stanislav Khlud <43534015+TheSuperiorStanislav@users.noreply.github.com> Date: Tue, 28 Jun 2022 21:22:46 +0700 Subject: [PATCH] Make autogenerated read only fields to be able to be nullable (#8536) --- rest_framework/utils/field_mapping.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/rest_framework/utils/field_mapping.py b/rest_framework/utils/field_mapping.py index 673821b5e..7e8e8f046 100644 --- a/rest_framework/utils/field_mapping.py +++ b/rest_framework/utils/field_mapping.py @@ -95,6 +95,9 @@ def get_field_kwargs(field_name, model_field): (hasattr(models, 'JSONField') and isinstance(model_field, models.JSONField)): kwargs['style'] = {'base_template': 'textarea.html'} + if model_field.null: + kwargs['allow_null'] = True + if isinstance(model_field, models.AutoField) or not model_field.editable: # If this field is read-only, then return early. # Further keyword arguments are not valid. @@ -104,9 +107,6 @@ def get_field_kwargs(field_name, model_field): if model_field.has_default() or model_field.blank or model_field.null: kwargs['required'] = False - if model_field.null: - kwargs['allow_null'] = True - if model_field.blank and (isinstance(model_field, (models.CharField, models.TextField))): kwargs['allow_blank'] = True @@ -263,6 +263,8 @@ def get_relation_kwargs(field_name, relation_info): if not model_field.editable: kwargs['read_only'] = True kwargs.pop('queryset', None) + if model_field.null: + kwargs['allow_null'] = True if kwargs.get('read_only', False): # If this field is read-only, then return early. # No further keyword arguments are valid. @@ -270,8 +272,6 @@ def get_relation_kwargs(field_name, relation_info): if model_field.has_default() or model_field.blank or model_field.null: kwargs['required'] = False - if model_field.null: - kwargs['allow_null'] = True if model_field.validators: kwargs['validators'] = model_field.validators if getattr(model_field, 'unique', False):