基于默认的 allauth 模板,我想构建一个自定义注册表单,其中还包括 ChoiceField 和 ModelChoiceField。因此我做了以下调整:
账户/模型.py
class Country(models.Model):
name = models.CharField(max_length=20, unique=True)
def __str__(self):
return self.name
class CustomUser(AbstractUser):
SALUTATION = (
('m', _('Mr')),
('f', _('Mrs')),
)
salutation = models.CharField(
max_length=1,
choices=SALUTATION,
blank=True,
null=True
)
country = models.ForeignKey(
Country,
on_delete=models.PROTECT,
verbose_name=_('Country'),
blank=True,
null=True
)
账户/表单.py
class CustomSignupForm(forms.Form):
salutation = forms.ChoiceField(widget=Select, choices=CustomUser.SALUTATION, initial=CustomUser.SALUTATION)
country = forms.ModelChoiceField(queryset=Country.objects.all(), initial=Country.objects.all())
templates/allauth/elements/field.html
{% load allauth %}
{% if attrs.type == "select" %}
<select name="{{ attrs.name }}" id="{{ attrs.id }}" class="form-select mb-3">
{% for option in attrs.value %}
<option value="{% if option.0 %}{{ option.0 }}{% else %}{{ option.id }}{% endif %}">
{% if option.1 %}
{{ option.1 }}
{% else %}
{{ option }}
{% endif %}
</option>
{% endfor %}
</select>
{% elif attrs.type == "checkbox" or attrs.type == "radio" %}
...
仅在表单中传递“初始”参数时,选项才会填充到 attrs.value 中。这不应该由“choices”或“queryset”参数提供吗?是否可以选择以不同的方式从 attrs 对象获取值?
initial=…
[Django-doc] 需要 one 元素,现在你传递了所有元素,所以是一个 collection 元素,所以:
class CustomSignupForm(forms.Form):
salutation = forms.ChoiceField(
widget=Select,
choices=CustomUser.SALUTATION,
initial=CustomUser.SALUTATION,
)
country = forms.ModelChoiceField(
queryset=Country.objects.all(),
initial=Country.objects.get('United States'),
)