草庐IT

Django EmbeddedModelField 在执行 PUT 请求时说 "This field may not be blank",尽管字段具有 "blank=True"

coder 2023-11-02 原文

我正在使用 django-rest-framework 创建 Django 应用程序并使用 djongo 连接到 MongoDB。我有这样的嵌套模型:

class Group(models.Model):
    users = models.ArrayModelField(
        model_container=User
    )

class User(models.Model):
    number = models.IntegerField(
        default=None,
        null=True
    )

    song = models.EmbeddedModelField(
        model_container=Song,
        null=True,
        blank=True
    )

    class Meta:
        abstract = True

class Song(models.Model):
    mp3_file = models.URLField(
        default=None,
        blank=True,
        null=True
    )

    comments = models.CharField(
        max_length=250,
        default='',
        blank=True
    )

    class Meta:
        abstract = True

创建组时,用户和歌曲的创建没有任何问题。例如,创建时,组可能如下所示:

{
    "name": "Sample",
    "users: [
        {
            "number": null,
            "song": {
                "mp3_file": null,
                "comments": ""
            }
        }
    ]
}

一切正常。但是,如果我尝试执行 PUT 请求并且不更改“number”、“mp3_file”或“comments”的值,我将收到以下错误消息:

"user": [
    {
        "number": [
            "This field may not be null."
        ],
        "song": {
            "mp3_file": [
                "This field may not be null."
            ],
            "comments": [
                "This field may not be blank."
            ]
        }
    }
]

关于如何修复此错误的任何想法?我只是使用通用的 RetrieveUpdateDestroyAPIView 作为此端点的 View 。

编辑:我也尝试过重新创建所有迁移以及删除表并重新创建它,但这些方法都没有帮助。

编辑: 这是 View :

class GroupDetail(generics.RetrieveUpdateDestroyAPIView):
    serializer_class = GroupSerializer
    queryset = Group.objects.all()
    lookup_field = 'group_name'
    lookup_url_kwarg = 'group_name'

还有序列化器:

class GroupSerializer(serializers.HyperlinkedModelSerializer):
    users = UserSerializer(many=True)

    def update(self, instance, validated_data):
        if validated_data.get('group_name', None) is not None:
            instance.__setattr__('group_name', validated_data.get('group_name'))

        instance.save()

        return instance

    class Meta:
        model = Group
        fields = (
            'group_name',
            'users'
        )


class UserSerializer(serializers.Serializer):
    number = serializers.IntegerField()
    song = SongSerializer()


class SongSerializer(serializers.Serializer):
    mp3_file = serializers.URLField()
    comments = serializers.CharField(
        max_length=250
    )

但部分问题在于,由于数据验证不正确,甚至从未访问过序列化器。

最佳答案

尝试改变:

class UserSerializer(serializers.Serializer):
    number = serializers.IntegerField(allow_null=True)
    song = SongSerializer()

class SongSerializer(serializers.Serializer):
    mp3_file = serializers.URLField(allow_blank=True)
    comments = serializers.CharField(
        max_length=250, allow_blank=True
    )

关于Django EmbeddedModelField 在执行 PUT 请求时说 "This field may not be blank",尽管字段具有 "blank=True",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54375572/

有关Django EmbeddedModelField 在执行 PUT 请求时说 "This field may not be blank",尽管字段具有 "blank=True"的更多相关文章

  1. ruby-on-rails - rails : "missing partial" when calling 'render' in RSpec test - 2

    我正在尝试测试是否存在表单。我是Rails新手。我的new.html.erb_spec.rb文件的内容是:require'spec_helper'describe"messages/new.html.erb"doit"shouldrendertheform"dorender'/messages/new.html.erb'reponse.shouldhave_form_putting_to(@message)with_submit_buttonendendView本身,new.html.erb,有代码:当我运行rspec时,它失败了:1)messages/new.html.erbshou

  2. ruby-on-rails - 由于 "wkhtmltopdf",PDFKIT 显然无法正常工作 - 2

    我在从html页面生成PDF时遇到问题。我正在使用PDFkit。在安装它的过程中,我注意到我需要wkhtmltopdf。所以我也安装了它。我做了PDFkit的文档所说的一切......现在我在尝试加载PDF时遇到了这个错误。这里是错误:commandfailed:"/usr/local/bin/wkhtmltopdf""--margin-right""0.75in""--page-size""Letter""--margin-top""0.75in""--margin-bottom""0.75in""--encoding""UTF-8""--margin-left""0.75in""-

  3. ruby-openid:执行发现时未设置@socket - 2

    我在使用omniauth/openid时遇到了一些麻烦。在尝试进行身份验证时,我在日志中发现了这一点:OpenID::FetchingError:Errorfetchinghttps://www.google.com/accounts/o8/.well-known/host-meta?hd=profiles.google.com%2Fmy_username:undefinedmethod`io'fornil:NilClass重要的是undefinedmethodio'fornil:NilClass来自openid/fetchers.rb,在下面的代码片段中:moduleNetclass

  4. ruby - 具有身份验证的私有(private) Ruby Gem 服务器 - 2

    我想安装一个带有一些身份验证的私有(private)Rubygem服务器。我希望能够使用公共(public)Ubuntu服务器托管内部gem。我读到了http://docs.rubygems.org/read/chapter/18.但是那个没有身份验证-如我所见。然后我读到了https://github.com/cwninja/geminabox.但是当我使用基本身份验证(他们在他们的Wiki中有)时,它会提示从我的服务器获取源。所以。如何制作带有身份验证的私有(private)Rubygem服务器?这是不可能的吗?谢谢。编辑:Geminabox问题。我尝试“捆绑”以安装新的gem..

  5. ruby - 检查 "command"的输出应该包含 NilClass 的意外崩溃 - 2

    为了将Cucumber用于命令行脚本,我按照提供的说明安装了arubagem。它在我的Gemfile中,我可以验证是否安装了正确的版本并且我已经包含了require'aruba/cucumber'在'features/env.rb'中为了确保它能正常工作,我写了以下场景:@announceScenario:Testingcucumber/arubaGivenablankslateThentheoutputfrom"ls-la"shouldcontain"drw"假设事情应该失败。它确实失败了,但失败的原因是错误的:@announceScenario:Testingcucumber/ar

  6. ruby-on-rails - 如何验证非模型(甚至非对象)字段 - 2

    我有一个表单,其中有很多字段取自数组(而不是模型或对象)。我如何验证这些字段的存在?solve_problem_pathdo|f|%>... 最佳答案 创建一个简单的类来包装请求参数并使用ActiveModel::Validations。#definedsomewhere,atthesimplest:require'ostruct'classSolvetrue#youcouldevencheckthesolutionwithavalidatorvalidatedoerrors.add(:base,"WRONG!!!")unlesss

  7. ruby-on-rails - form_for 中不在模型中的自定义字段 - 2

    我想向我的Controller传递一个参数,它是一个简单的复选框,但我不知道如何在模型的form_for中引入它,这是我的观点:{:id=>'go_finance'}do|f|%>Transferirde:para:Entrada:"input",:placeholder=>"Quantofoiganho?"%>Saída:"output",:placeholder=>"Quantofoigasto?"%>Nota:我想做一个额外的复选框,但我该怎么做,模型中没有一个对象,而是一个要检查的对象,以便在Controller中创建一个ifelse,如果没有检查,请帮助我,非常感谢,谢谢

  8. ruby - Chef 执行非顺序配方 - 2

    我遵循了教程http://gettingstartedwithchef.com/,第1章。我的运行list是"run_list":["recipe[apt]","recipe[phpap]"]我的phpapRecipe默认Recipeinclude_recipe"apache2"include_recipe"build-essential"include_recipe"openssl"include_recipe"mysql::client"include_recipe"mysql::server"include_recipe"php"include_recipe"php::modul

  9. ruby-on-rails - 迷你测试错误 : "NameError: uninitialized constant" - 2

    我遵循MichaelHartl的“RubyonRails教程:学习Web开发”,并创建了检查用户名和电子邮件长度有效性的测试(名称最多50个字符,电子邮件最多255个字符)。test/helpers/application_helper_test.rb的内容是:require'test_helper'classApplicationHelperTest在运行bundleexecraketest时,所有测试都通过了,但我看到以下消息在最后被标记为错误:ERROR["test_full_title_helper",ApplicationHelperTest,1.820016791]test

  10. ruby-on-rails - 在 Rails 和 ActiveRecord 中查询时忽略某些字段 - 2

    我知道我可以指定某些字段来使用pluck查询数据库。ids=Item.where('due_at但是我想知道,是否有一种方法可以指定我想避免从数据库查询的某些字段。某种反拔?posts=Post.where(published:true).do_not_lookup(:enormous_field) 最佳答案 Model#attribute_names应该返回列/属性数组。您可以排除其中一些并传递给pluck或select方法。像这样:posts=Post.where(published:true).select(Post.attr

随机推荐