您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Django ManyToMany模型验证

Django ManyToMany模型验证

无法在模型的clean方法中进行此验证,但是你可以创建一个模型表单来验证的选择words

from django import forms

class SentenceForm(forms.ModelForm):
    class Meta:
        model = Sentence

    def clean(self):
        """
        Checks that all the words belong to the sentence's language.
        """
        words = self.cleaned_data.get('words')
        language = self.cleaned_data.get('language')
        if language and words:
            # only check the words if the language is valid
            for word in words:
                if words.language != language:
                    raise ValidationError("The word %s has a different language" % word)
        return self.cleaned_data

然后,你可以自定义Sentence模型管理员类,以在Django管理员中使用表单。

class SentenceAdmin(admin.ModelAdmin):
    form = SentenceForm

admin.register(Sentence, SentenceAdmin)
Go 2022/1/1 18:13:57 有640人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶