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?
Conditional logic in regards to forms is a way to create forms that change based on input. You can configure fields to display or hide based on a user's response to other fields. This allows you to tailor your forms to your users' specific needs.
Go into edit your form. Open the Field Options for the field that you want to conditionally show or hide. Select Use Conditional Logic and set it up to "Show this field if any of the following match". For example, you may want to display an HTML field message when a certain email address is entered.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With