gpt4 book ai didi

python - Django 。 UserCreationForm 未正确呈现

转载 作者:行者123 更新时间:2023-11-30 23:13:56 24 4
gpt4 key购买 nike

对我来说这很奇怪,也许不是,我错过了一些明显的东西:

forms.py

from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm

class formRegistro(UserCreationForm):
class Meta:
model = User
fields = ("first_name", "last_name", "email", "username", "password1", "password2")
widgets = {
'first_name': forms.TextInput(attrs={'class':'form-control'}),
'last_name': forms.TextInput(attrs={'class':'form-control'}),
'email': forms.TextInput(attrs={'class':'form-control'}),
'username': forms.TextInput(attrs={'class':'form-control'}),
'password1': forms.PasswordInput(attrs={'class':'form-control'}),
'password2': forms.PasswordInput(attrs={'class':'form-control'})
}

views.py

def registro(request):    
template = "perfiles/registro.html"
form = formRegistro()
context = {'form' : form}
return render(request, template, context)

html registro.html

<form class="form-horizontal" action="{% url 'perfiles:registro' %}" method="post">
{% csrf_token %}
<fieldset>
{{form}}
</fieldset>
<input type="submit" value="Submit">
</form>

对我来说看起来不错,我只是渲染一个表单。我想要的只是将“表单控制”添加到输入的类中。奇怪的是,它只将“form-control”添加到“first_name”、“last_name”和“email_address”字段中。 ?¡ 输入“用户名”、“密码1”和“密码2”没有表单控制类。

这是渲染的 html: screenshot

最佳答案

如果您查看UserCreationForm的源代码,您将看到这三个字段是声明性定义的:

class UserCreationForm(forms.ModelForm):
...
username = forms.RegexField(...)
password1 = forms.CharField(...)
password2 = forms.CharField(...)
...

根据the documentation ,您不能在 Meta 中覆盖它们:

Fields defined declaratively are left as-is, therefore any customizations made to Meta attributes such as widgets, labels, help_texts, or error_messages are ignored; these only apply to fields that are generated automatically.

因此,您最好的选择是将这些声明复制到您自己的类中并覆盖其中的小部件选项。

更新:另一种选择是按照@catavaran的建议修改表单的__init__方法中的小部件属性。请参阅this answer举个例子。

关于python - Django 。 UserCreationForm 未正确呈现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29022765/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com