我需要能夠以更加用戶友好的方式顯示有關無效小數和無效外鍵的錯誤。
我以為它clean_model_instances = True會抓住它,但它沒有。
無效的十進制錯誤:

外鍵無效錯誤:

我想顯示的是錯誤以及此處的所有其他錯誤:

提前致謝!
uj5u.com熱心網友回復:
有幾種方法可以解決這個問題。
對于將其
DecimalWidget宣告為CharWidget- 這將處理任何輸入字串,如果您已clean_model_instances啟用,則在驗證模型物件時將引發錯誤。對于
ForeignKeyWidget,您將必須覆寫該clean()方法,以便它ValueError為不存在的參考引發 a 。IMO 這并不理想,因為它違反了該clean()功能的合同。錯誤訊息并不完美,但它確實實作了您想要的。
class ValidatingForeignKeyWidget(widgets.ForeignKeyWidget):
def clean(self, value, row=None, *args, **kwargs):
try:
val = super().clean(value)
except self.model.DoesNotExist:
raise ValueError(f"{self.model.__name__} with value={value} does not exist")
return val
class BookResource(ModelResource):
price = fields.Field(attribute='price', widget=widgets.CharWidget())
author = fields.Field(attribute="author", widget=ValidatingForeignKeyWidget(Author))
class Meta:
model = Book
clean_model_instances = True

轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/340296.html
