Django - 管理/添加运行 model.clean 即使字段丢失
好的,我有一个这样的模型:
class Airplane(models.Model):
tail = models.ForeignKey(Tails)
wheel = models.CharField(max_length=500,blank=True)
window = models.CharField(max_length=500,blank=True)
def clean(self):
if self.tail and self.wheel and self.window:
raise ValidationError("Can't have all three, choose tail and one more")
现在,如果我使用 Django admin 添加新的飞机记录。如果我将两个字段留空并保存,我会收到此 Django 错误,指向 if self.tail and self.wheel
行。
DoesNotExist at /admin/MyProject/airplane/add/
Request Method: POST
Request URL: http://44.101.44.172:8001/admin/MyProject/airplane/add/
Django Version: 1.2.5
Exception Type: DoesNotExist
Exception Value:
Exception Location: /usr/lib/python2.7/site-packages/django/db/models/fields/related.py in __get__, line 299
Python Executable: /usr/bin/python
Python Version: 2.7.0
Django 不应该在运行 clean 之前检查必填字段是否已填写吗?无论如何,处理这个问题的最佳方法是什么?
Ok, so I have a model like this:
class Airplane(models.Model):
tail = models.ForeignKey(Tails)
wheel = models.CharField(max_length=500,blank=True)
window = models.CharField(max_length=500,blank=True)
def clean(self):
if self.tail and self.wheel and self.window:
raise ValidationError("Can't have all three, choose tail and one more")
Now if I go to add a new Airplane record using Django admin. If I leave both fields blank and save I get this Django error pointing to the line if self.tail and self.wheel
.
DoesNotExist at /admin/MyProject/airplane/add/
Request Method: POST
Request URL: http://44.101.44.172:8001/admin/MyProject/airplane/add/
Django Version: 1.2.5
Exception Type: DoesNotExist
Exception Value:
Exception Location: /usr/lib/python2.7/site-packages/django/db/models/fields/related.py in __get__, line 299
Python Executable: /usr/bin/python
Python Version: 2.7.0
Shouldn't Django be checking that the required fields are filled in before running clean? In any case, what's the best way to handle this issue?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的 tails 字段不接受空值。您需要添加
null=True
才能使其正常工作。Your tails field does not accept null values. You will need to add
null=True
to it to make it work.好的,作为一种解决方法,我最终定义了 自定义表单 与 我的验证 在该模型的 admin.py 中。
我仍然不明白为什么在 Django 确定必填字段已填写之前 model.clean 被调用。哦,好吧。
Ok, as a workaround I ended up defining a custom form with my validation in admin.py for this model.
I still don't understand why model.clean gets called before Django has determined that the required fields have been filled in. Oh well.