django-allauth:重新排列表单字段(更改顺序)

6
我将使用django-allauth进行用户注册。我有以下表单:
class UserProfileForm(forms.ModelForm):
class Meta:
    model = UserProfile
    fields = ('gender', 'country', 'city', 'birth_date', 'has_accepted_tos')

根据我的设置文件(settings.py)的指示,我已经进行了设置。
ACCOUNT_SIGNUP_FORM_CLASS = "userprofile.forms.UserProfileForm"

问题在于,表单呈现时,我的自定义表单要求填写性别、国家等信息显示在顶部,而标准的用户字段要求填写用户名、电子邮件和密码。以某种次序如下:
  • 性别

  • 国家

  • 城市

  • 出生日期

  • 是否同意服务条款

  • 用户名

  • 电子邮件

  • 密码1

  • 密码2

    我希望按照以下顺序显示字段:

  • 用户名

  • 电子邮件

  • 密码1

  • 密码2

  • 性别

  • 国家

  • 等等


请为第二个问题创建一个单独的问题,并将其从这里删除。 - mariodev
好的,我已经删除了第二个问题。 - voger
1个回答

8
您需要提供field_order属性:
class UserProfileForm(forms.ModelForm):
    class Meta:
        model = UserProfile
        fields = ('gender', 'country', 'city', 'birth_date', 'has_accepted_tos')
        field_order = ['username', 'email', 'password1', 'password2', 'gender', 'country']

然而,更好的做法是使用模板文件来精确渲染表单。

引用项目作者的话:

(...) 再说一遍,我不会过多关注allauth在显示/设计方面提供的功能。所有这些都只是参考,重点是您在模板中创建适当的设计和表单布局。

参考资料:

[1] https://github.com/pennersr/django-allauth/blob/master/allauth/account/forms.py

[2] https://github.com/pennersr/django-allauth/issues/269


谢谢。最终我选择了第二种方法,按照我想要的方式呈现模板。我只是不知道我可以这样做。 - voger
嗨,从阅读[1]中的代码来看,field_order不应该放在“Meta”上,而是应该放在类本身上? - Dimitrios Mistriotis

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接