条件字段的形式 [英] Conditional field in form

查看:133
本文介绍了条件字段的形式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要根据用户是否登录,制作一个可能没有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,我无法访问表单创建/定义上的请求对象,所以我不能依赖这个。

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>

但我不想在每个评论中重复该代码/ * / form.html 模板。我收集应该有一些方法从小部件的 render 方法和媒体定义添加等效的代码。

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应用程序中一样 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆