Django:如何检查自定义小部件定义中是否存在字段错误?
我想创建在关联字段出现错误时将特定类添加到元素标记的小部件。
我很难找到有关如何从小部件定义代码中检查字段是否有与其关联的错误的信息。
目前我有以下存根小部件代码(最终的小部件将使用更复杂的标记)。
from django import forms
from django.utils.safestring import mark_safe
class CustomTextWidget(forms.Widget):
def render(self, name, value, attrs):
field_has_errors=False # change to dynamically reflect field errors, somehow
if field_has_errors:
error_class_string="error"
else:
error_class_string=""
return mark_safe(
"<input type=\"text\" class=\"%s\" value=\"%s\" id=\"id_%s\" name=\"%s\">" % (error_class_string, value, name, name)
)
任何人都可以阐明这里填充 field_has_errors 布尔值的明智方法吗? (或者也许建议一种更好的方法来完成我想做的事情)。提前致谢。
I'd like to create widgets that add specific classes to element markup when the associated field has errors.
I'm having a hard time finding information on how to check whether a field has errors associated with it, from within widget definition code.
At the moment I have the following stub widget code (the final widget will use more complex markup).
from django import forms
from django.utils.safestring import mark_safe
class CustomTextWidget(forms.Widget):
def render(self, name, value, attrs):
field_has_errors=False # change to dynamically reflect field errors, somehow
if field_has_errors:
error_class_string="error"
else:
error_class_string=""
return mark_safe(
"<input type=\"text\" class=\"%s\" value=\"%s\" id=\"id_%s\" name=\"%s\">" % (error_class_string, value, name, name)
)
Can anyone shed light on a sensible way to populate the field_has_errors Boolean here? (or perhaps suggest a better way to accomplish what I'm trying to do). Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
小部件不知道它所应用的领域。它是维护有关错误的信息的字段。您可以在表单的 init 方法中检查 error_messages,并相应地将错误类注入到您的小部件中:
The widget has no knowledge of the field to which it is being applied. It is the field that maintains information about errors. You can check for error_messages in the init method of your form, and inject an error class to your widget accordingly:
正如 Jason 所说,小部件无法访问该字段本身。我认为更好的解决方案是使用 CSS 的级联特性。
现在在你的 CSS 中你可以做:
或任何你需要的事情。
As Jason says, the widget has no access to the field itself. I think a better solution though is to use the cascading nature of CSS.
Now in your CSS you can do:
or whatever you need.