Django:在测试模式下以不同的方式定义表单
我有一个自定义的验证码字段。我想在测试期间显示该字段时从表单中删除该字段。
我最初的想法是在单独的设置文件中添加一个 TESTING
变量,该变量将作为参数提供给测试运行器命令。然后,我可以这样说:
class CaptchaForm(forms.Form):
notify_email = forms.EmailField(required=False)
if not settings.TESTING:
recaptcha = CaptchaField()
我相信这应该有效。
可能有更好的方法。有什么想法吗?
更新
在尝试了下面的建议后,我将其添加到测试文件夹的 __init__.py
中:
from project.app.forms import CaptchaField
CaptchaField.clean = lambda x, y: y
这有效——无需创建共享的 TESTING
设置。这看起来可以接受吗?我有理由不应该这样做吗?
I have a customized captcha field. I want to remove that field from a form when displaying it during tests.
My initial thought was to have a TESTING
variable in a separate settings file that will be supplied as an argument to the test runner command. Then, I could to something like:
class CaptchaForm(forms.Form):
notify_email = forms.EmailField(required=False)
if not settings.TESTING:
recaptcha = CaptchaField()
I believe this should work.
There might be an even better approach. Any ideas?
Update
After playing around with the suggestions below, I added this to the test folder's __init__.py
:
from project.app.forms import CaptchaField
CaptchaField.clean = lambda x, y: y
This worked---without creating a shared TESTING
setting. Does this look acceptable? Is there a reason that I should not do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以在单元测试类的构造函数中禁用验证码。像这样:
或者例如,您可以在此构造函数中禁用验证码字段验证。
You can disable captcha in constructor of unit-testing class. Like this:
Or you can disable captcha field validation in this constructor, for example.
我假设 CaptchaField 是您自己的类。然后您可以更改验证方法:
正如 were human 已经提到的,您实际上并不需要单独的设置文件,但可以更改单元测试类内的设置。
I assume
CaptchaField
is your own class. Then you could change the validation method:As werehuman already mentioned, you don't really need a separate settings file but can change the setting inside the unit test class.