我能够在我的Django-allauth注册表单上获得noRecaptcha表单,模板使用crispy表单。 Using this answer
问题实际上是关于在表单包含在django-allauth中并且没有指定布局(根据作者)的情况下在crispy表单布局上强制字段顺序。因此,当使用我自己的自定义形式覆盖注册表单时,我已尝试指定布局,但我不确定我是否已将其识别出来。
结合其他帖子的答案:
from django import forms
from neatf.users.models import User
from nocaptcha_recaptcha.fields import NoReCaptchaField
class AllauthSignupForm(forms.Form):
captcha = NoReCaptchaField()
class Meta:
model = User
fields = ['username', 'email', 'password1', 'password2', 'captcha']
field_order = ['username', 'email', 'password1', 'password2',
'captcha']
def signup(self, request, user):
""" Required, or else it throws deprecation warnings """
pass
我确定我引用了错误的模型,或者它被忽略了。 noRecaptcha字段恰好位于表单的顶部,而不是位于我喜欢的底部。
我也尝试过使用FormHelper - 但显然必须做错了。
helper = FormHelper()
helper.form_class = '.form-inline'
helper.field_template = 'bootstrap4/layout/inline_field.html'
helper.layout = Layout(
Fieldset('Contact data', 'username', 'email',),
Fieldset('Password', 'password1', 'password2', 'captcha'))
我宁愿不重写模板,希望有办法覆盖布局。
答案 0 :(得分:0)
以前寻找此问题的解决方案并使用此方法:
class AllauthSignupForm(forms.Form):
#https://developers.google.com/recaptcha/docs/display
#https://github.com/praekelt/django-recaptcha
captcha = ReCaptchaField(
attrs={
'theme' : 'clean',
'size' : 'normal', #compact
})
captcha.label = "Капча"
def __init__(self, *args, **kwargs):
super(AllauthSignupForm, self).__init__(*args, **kwargs)
original_fields = self.fields
new_order = OrderedDict()
for key in ['username', 'email', 'password1', 'password2', 'captcha']:
if key in original_fields:
new_order[key] = original_fields[key]
self.fields = new_order
def signup(self, request, user):
""" Required, or else it throws deprecation warnings """
pass
相关答案:
How does Django Know the Order to Render Form Fields?
How can I order fields in Django ModelForm?
django-allauth: rearrange form fields (change order)
该解决方案适用于版本 django-allauth == 0.29 ,并且在新版本中不起作用
(测试0.30-0.31)
对于新版本,我无法设置订单。
答案 1 :(得分:0)
我在github上关于django-crispy的报道问题中找到了答案。一个"undocumented" feature(当时)我终于found in the docs on tags reference(布局部分没有提到)。
非常简单并且在模板上完成,需要对forms.py:
进行零更改<强> signup.html 强>
<form class="signup" id="signup_form" method="post" action="{% url 'account_signup' %}">
{% csrf_token %}
{{ form.username|as_crispy_field }}
{{ form.email|as_crispy_field }}
{{ form.password1|as_crispy_field }}
{{ form.password2|as_crispy_field }}
{{ form.captcha|as_crispy_field }}
{% if redirect_field_value %}
<input type="hidden" name="{{ redirect_field_name }}" value="{{ redirect_field_value }}"/>
{% endif %}
<script src='https://www.google.com/recaptcha/api.js'></script>
<button class="btn btn-primary" type="submit">{% trans "Sign Up" %} »</button>
</form>
<强> forms.py 强>
from django import forms
from nocaptcha_recaptcha.fields import NoReCaptchaField
class AllauthSignupForm(forms.Form):
captcha = NoReCaptchaField()
def signup(self, request, user):
""" Required, or else it throws deprecation warnings """
pass
希望这有助于其他人。