Django DRF display field's verbose_name in error messageAuto-truncating fields at max_length in Django CharFieldsDjango: How to override unique_together error message?Can't add field to ModelForm at __init__Django: Display a custom error message for admin validation errordjango list of all possible error messages which a CharField form validator can raise?Django Rest Framework 2.4 TypeError: __init__() got an unexpected keyword argument 'allow_none'Using ModelSerializer with DRF and Class-based View returns Attribute ErrorHow can intercept base field validation before own validationHow to implement update_or_create inside create method of ModelSerializerdjango-tables doesn't display foreign-key as link in gcbv ListView

Deck of Cards with Shuffle and Sort functionality

Was it ever illegal to name a pig "Napoleon" in France?

Is "wissen" the only verb in German to have an irregular present tense?

What exactly is a "murder hobo"?

What does the multimeter dial do internally?

Is there an In-Universe reason why Thor and the Asgardians think Rocket is a rabbit?

What is the relationship between external and internal composition in a cartesian closed category?

My previous employer committed a severe violation of the law and is also being sued by me. How do I explain the situation to future employers?

How to evaluate the performance of open source solver?

Where are the Wazirs?

Passwordless authentication - how and when to invalidate a login code

Draw a diagram with rectangles

Why won't the U.S. sign a peace treaty with North Korea?

What was the nature of the known bugs in the Space Shuttle software?

How do I explain that I don't want to maintain old projects?

Is this really the Saturn V computer only, or are there other systems here as well?

Delete elements less than the last largest element

What was the profession 芸者 (female entertainer) called in Russia?

What was the significance of Spider-Man: Far From Home being an MCU Phase 3 film instead of a Phase 4 film?

Why is a mixture of two normally distributed variables only bimodal if their means differ by at least two times the common standard deviation?

How does one acquire an undead eyeball encased in a gem?

What's the adjective used to qualify a software that's available on your first boot?

Need a non-volatile memory IC with near unlimited read/write operations capability

How should I ask for a "pint" in countries that use metric?



Django DRF display field's verbose_name in error message


Auto-truncating fields at max_length in Django CharFieldsDjango: How to override unique_together error message?Can't add field to ModelForm at __init__Django: Display a custom error message for admin validation errordjango list of all possible error messages which a CharField form validator can raise?Django Rest Framework 2.4 TypeError: __init__() got an unexpected keyword argument 'allow_none'Using ModelSerializer with DRF and Class-based View returns Attribute ErrorHow can intercept base field validation before own validationHow to implement update_or_create inside create method of ModelSerializerdjango-tables doesn't display foreign-key as link in gcbv ListView






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








1















When model field validation fail, I would like DRF to return the field verbose_name in the error message.



example :



models.py :



class MyClass(models.Model):
myfield = model.CharField(max_length=20,
verbose_name="This is the field",
default="blabla")


serialiers.py :



class MyClassSerializer(serializers.ModelSerializer):
class Meta:
model = MyClass
fields = ('myfield',)


If, POSTED data for this field is more than 20 characters, response payload is:



"myfield":["the error message..........."]


To make a friendlier message for the users (... and easily manage the errors :-) ) , I'd like to use the model field's verbose_name, so the response payload would be :



"This is the field":["the error message..........."]


Do you have any idea?
Thanks!










share|improve this question




























    1















    When model field validation fail, I would like DRF to return the field verbose_name in the error message.



    example :



    models.py :



    class MyClass(models.Model):
    myfield = model.CharField(max_length=20,
    verbose_name="This is the field",
    default="blabla")


    serialiers.py :



    class MyClassSerializer(serializers.ModelSerializer):
    class Meta:
    model = MyClass
    fields = ('myfield',)


    If, POSTED data for this field is more than 20 characters, response payload is:



    "myfield":["the error message..........."]


    To make a friendlier message for the users (... and easily manage the errors :-) ) , I'd like to use the model field's verbose_name, so the response payload would be :



    "This is the field":["the error message..........."]


    Do you have any idea?
    Thanks!










    share|improve this question
























      1












      1








      1








      When model field validation fail, I would like DRF to return the field verbose_name in the error message.



      example :



      models.py :



      class MyClass(models.Model):
      myfield = model.CharField(max_length=20,
      verbose_name="This is the field",
      default="blabla")


      serialiers.py :



      class MyClassSerializer(serializers.ModelSerializer):
      class Meta:
      model = MyClass
      fields = ('myfield',)


      If, POSTED data for this field is more than 20 characters, response payload is:



      "myfield":["the error message..........."]


      To make a friendlier message for the users (... and easily manage the errors :-) ) , I'd like to use the model field's verbose_name, so the response payload would be :



      "This is the field":["the error message..........."]


      Do you have any idea?
      Thanks!










      share|improve this question














      When model field validation fail, I would like DRF to return the field verbose_name in the error message.



      example :



      models.py :



      class MyClass(models.Model):
      myfield = model.CharField(max_length=20,
      verbose_name="This is the field",
      default="blabla")


      serialiers.py :



      class MyClassSerializer(serializers.ModelSerializer):
      class Meta:
      model = MyClass
      fields = ('myfield',)


      If, POSTED data for this field is more than 20 characters, response payload is:



      "myfield":["the error message..........."]


      To make a friendlier message for the users (... and easily manage the errors :-) ) , I'd like to use the model field's verbose_name, so the response payload would be :



      "This is the field":["the error message..........."]


      Do you have any idea?
      Thanks!







      django django-rest-framework






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Mar 25 at 22:30









      stockerskystockersky

      5411 gold badge4 silver badges22 bronze badges




      5411 gold badge4 silver badges22 bronze badges






















          1 Answer
          1






          active

          oldest

          votes


















          1














          I dont think there is an easy way of doing this. The easiest way would be overriding errors property of serializer and changing error keys with verbose name.



          class TestSerializer(serializers.ModelSerializer):
          class Meta:
          model = ...
          fields = ('field1', ...)

          @property
          def errors(self):
          # get errors
          errors = super().errors
          verbose_errors =

          # fields = field.name: field.verbose_name for each field in model
          fields = field.name: field.verbose_name for field in
          self.Meta.model._meta.get_fields() if hasattr(field, 'verbose_name')

          # iterate over errors and replace error key with verbose name if exists
          for field_name, error in errors.items():
          if field_name in fields:
          verbose_errors[str(fields[field_name])] = error
          else:
          verbose_errors[field_name] = error
          return verbose_errors





          share|improve this answer























          • Thanks for your answer. Finally, as I use Vue.js on the frontend, I choose to use Vee Validate. This way, POSTED data is validated on the backend AND the browser. As invalid data isn't posted, this is even lighter for the backend API.

            – stockersky
            Mar 26 at 19:41











          Your Answer






          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "1"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55347324%2fdjango-drf-display-fields-verbose-name-in-error-message%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          1














          I dont think there is an easy way of doing this. The easiest way would be overriding errors property of serializer and changing error keys with verbose name.



          class TestSerializer(serializers.ModelSerializer):
          class Meta:
          model = ...
          fields = ('field1', ...)

          @property
          def errors(self):
          # get errors
          errors = super().errors
          verbose_errors =

          # fields = field.name: field.verbose_name for each field in model
          fields = field.name: field.verbose_name for field in
          self.Meta.model._meta.get_fields() if hasattr(field, 'verbose_name')

          # iterate over errors and replace error key with verbose name if exists
          for field_name, error in errors.items():
          if field_name in fields:
          verbose_errors[str(fields[field_name])] = error
          else:
          verbose_errors[field_name] = error
          return verbose_errors





          share|improve this answer























          • Thanks for your answer. Finally, as I use Vue.js on the frontend, I choose to use Vee Validate. This way, POSTED data is validated on the backend AND the browser. As invalid data isn't posted, this is even lighter for the backend API.

            – stockersky
            Mar 26 at 19:41
















          1














          I dont think there is an easy way of doing this. The easiest way would be overriding errors property of serializer and changing error keys with verbose name.



          class TestSerializer(serializers.ModelSerializer):
          class Meta:
          model = ...
          fields = ('field1', ...)

          @property
          def errors(self):
          # get errors
          errors = super().errors
          verbose_errors =

          # fields = field.name: field.verbose_name for each field in model
          fields = field.name: field.verbose_name for field in
          self.Meta.model._meta.get_fields() if hasattr(field, 'verbose_name')

          # iterate over errors and replace error key with verbose name if exists
          for field_name, error in errors.items():
          if field_name in fields:
          verbose_errors[str(fields[field_name])] = error
          else:
          verbose_errors[field_name] = error
          return verbose_errors





          share|improve this answer























          • Thanks for your answer. Finally, as I use Vue.js on the frontend, I choose to use Vee Validate. This way, POSTED data is validated on the backend AND the browser. As invalid data isn't posted, this is even lighter for the backend API.

            – stockersky
            Mar 26 at 19:41














          1












          1








          1







          I dont think there is an easy way of doing this. The easiest way would be overriding errors property of serializer and changing error keys with verbose name.



          class TestSerializer(serializers.ModelSerializer):
          class Meta:
          model = ...
          fields = ('field1', ...)

          @property
          def errors(self):
          # get errors
          errors = super().errors
          verbose_errors =

          # fields = field.name: field.verbose_name for each field in model
          fields = field.name: field.verbose_name for field in
          self.Meta.model._meta.get_fields() if hasattr(field, 'verbose_name')

          # iterate over errors and replace error key with verbose name if exists
          for field_name, error in errors.items():
          if field_name in fields:
          verbose_errors[str(fields[field_name])] = error
          else:
          verbose_errors[field_name] = error
          return verbose_errors





          share|improve this answer













          I dont think there is an easy way of doing this. The easiest way would be overriding errors property of serializer and changing error keys with verbose name.



          class TestSerializer(serializers.ModelSerializer):
          class Meta:
          model = ...
          fields = ('field1', ...)

          @property
          def errors(self):
          # get errors
          errors = super().errors
          verbose_errors =

          # fields = field.name: field.verbose_name for each field in model
          fields = field.name: field.verbose_name for field in
          self.Meta.model._meta.get_fields() if hasattr(field, 'verbose_name')

          # iterate over errors and replace error key with verbose name if exists
          for field_name, error in errors.items():
          if field_name in fields:
          verbose_errors[str(fields[field_name])] = error
          else:
          verbose_errors[field_name] = error
          return verbose_errors






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Mar 26 at 0:07









          zeynelzeynel

          6203 silver badges12 bronze badges




          6203 silver badges12 bronze badges












          • Thanks for your answer. Finally, as I use Vue.js on the frontend, I choose to use Vee Validate. This way, POSTED data is validated on the backend AND the browser. As invalid data isn't posted, this is even lighter for the backend API.

            – stockersky
            Mar 26 at 19:41


















          • Thanks for your answer. Finally, as I use Vue.js on the frontend, I choose to use Vee Validate. This way, POSTED data is validated on the backend AND the browser. As invalid data isn't posted, this is even lighter for the backend API.

            – stockersky
            Mar 26 at 19:41

















          Thanks for your answer. Finally, as I use Vue.js on the frontend, I choose to use Vee Validate. This way, POSTED data is validated on the backend AND the browser. As invalid data isn't posted, this is even lighter for the backend API.

          – stockersky
          Mar 26 at 19:41






          Thanks for your answer. Finally, as I use Vue.js on the frontend, I choose to use Vee Validate. This way, POSTED data is validated on the backend AND the browser. As invalid data isn't posted, this is even lighter for the backend API.

          – stockersky
          Mar 26 at 19:41









          Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.







          Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.



















          draft saved

          draft discarded
















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid


          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.

          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55347324%2fdjango-drf-display-fields-verbose-name-in-error-message%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

          SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

          은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현