表单中的条件字段 [英] Conditional field in form
问题描述
我需要根据用户是否登录来创建一个可能有或没有 ReCaptcha 字段的 Form 类.
I need to make a Form class that may or not have a ReCaptcha field depending on whether the user is logged in or not.
因为这是一个 CommentForm,我无法访问表单创建/定义时的 request
对象,所以我不能依赖它.
Because this is a CommentForm, I have no access to the request
object on form creation/definition, so I can't rely on that.
对于 POST
请求,解决方案很简单:我有这个:
For the POST
request the solution is easy: I've got this:
class ReCaptchaCommentForm(CommentForm):
def __init__(self, data=None, *args, **kwargs):
super(ReCaptchaCommentForm, self).__init__(data, *args, **kwargs)
if data and 'recaptcha_challenge_field' in data:
self.fields['captcha'] = ReCaptchaField()
完成此操作后,表单验证应按预期工作.现在的问题是在模板方面.我需要这样的模板:
Having done this, form validation should work as intended. The problem now is on the template side. I need the template to be like this:
<form action={% comment_form_target %} method="post">
{# usual form stuff #}
{% if not user.is_authenticated %}
<script type="text/javascript"
src="http://www.google.com/recaptcha/api/js/recaptcha_ajax.js"></script>
<div id="recaptcha-div"></div>
<script type="text/javascript">
Recaptcha.create({{ public_key }}, "recaptcha-div",
{ theme: 'white',
callback: Recaptcha.focus_response_field });
</script>
{% endif %}
</form>
但我不想在每个 comments/*/form.html
模板上重复该代码.我认为应该有某种方法可以从小部件的 render
方法和 Media
定义中添加等效代码.
But I'd like not to have to repeat that code on every comments/*/form.html
template. I gather there should be some way of adding equivalent code from a widget's render
method and Media
definition.
谁能想到一个好的方法来做到这一点?
Can anyone think of a nice way to do this?
推荐答案
我假设您在视图中创建了表单,因此您可以将用户从请求传递到表单(就像在 auth app SetPassword 表单):
I assume that you instatiate your form in a view, so you could just pass the user from request to the form (just like in auth app SetPassword form):
def __init__(self, user, data=None, *args, **kwargs):
super(ReCaptchaCommentForm, self).__init__(data, *args, **kwargs)
if user.is_authenticated():
self.fields['captcha'] = ReCaptchaField()
这篇关于表单中的条件字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!