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.
Because this is a CommentForm, I have no access to the request
object on form creation/definition, so I can't rely on that.
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>
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?