如何使子类化的自定义 Django 表单字段成为非必需字段?
Django 文档 (http://docs.djangoproject.com/en/dev/ ref/forms/fields/) 说你可以创建 django.forms.Field 的子类,只要它实现 clean() 方法并且它的 init() 方法接受核心论点(必需、标签、首字母、小部件、帮助文本)。
我试图使用以下 Django 代码片段中的代码: http://djangosnippets.org/snippets/907/ 实现信用卡字段,但我希望它不是必需的。设置 required=false 对于普通字段来说效果很好,但对于此代码片段中的子类字段则不起作用。片段缺少什么? (我认为这是 init() 方法丢失或不接受 Django 文档中提到的核心参数,但我不知道如何解决这个问题。)
例如,将这些设置 required 为 false自定义字段,表单仍然需要它们:
CC_number = CreditCardField(required=False)
CC_expiration_date = CCExpField(required=False)
表单不需要此字段(它按预期工作):
CC_security_code = forms.IntegerField(required=False)
感谢您的帮助!
The Django docs (http://docs.djangoproject.com/en/dev/ref/forms/fields/) say that you can create a subclass of django.forms.Field as long as it implements a clean() method and its init() method accepts the core arguments (required, label, initial, widget, help_text).
I was trying to use the code in the following Django Snippet:
http://djangosnippets.org/snippets/907/
to implement a credit card field, but I want it to be non-required. Setting required=false works just fine for normal fields, but not for the subclassed fields in this snippet. What is the snippet missing? (I think it's init() method is missing or not accepting the core arguments mentioned in the Django docs, but I'm not sure how to fix this.)
For example, setting required to false on these custom fields, the form still requires them:
CC_number = CreditCardField(required=False)
CC_expiration_date = CCExpField(required=False)
The form doesn't require this field (it works as expected):
CC_security_code = forms.IntegerField(required=False)
Thanks for your help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
通过修改 CreditCardField 中的 clean 方法(方法的前 2 行),这应该可以工作:
This should work, by modifying the clean method in
CreditCardField
(first 2 lines of method):