Conditional field in the form

I need to create a Form class that may or may not have a ReCaptcha field, depending on whether the user is registered or not.

Since this is a CommentForm, I do not have access to the object requestwhen creating / defining the form, so I cannot rely on this.

For the request, the POSTsolution is easy: I have 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 is now on the template side. I need a template so that it is 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 would not want to repeat this code on every template comments/*/form.html. I am going to add some way to add equivalent code from the widget renderand definition method Media.

Can anyone think of a good way to do this?

+5
4

, , ( auth app SetPassword):

def __init__(self, user, data=None, *args, **kwargs):
    super(ReCaptchaCommentForm, self).__init__(data, *args, **kwargs)
    if user.is_authenticated():
        self.fields['captcha'] = ReCaptchaField()
+4

crispy-forms! html , / . .

doc.

+3

, , django-floppyforms . , , django-floppyforms .

, , , - . comments/form.html, comments/*/form.html. Recaptcha, , form.html, .

0

, , ( Form) .

, , . , , , .

0

All Articles