昨天我遇到了一个问题,试图覆盖Django注册应用程序的RegistrationForm。从DjangoUserCreationForm
类RegistrationForm
继承,这是基于ModelForm
,所以我创建了自定义类以这种方式从RegistrationForm
继承:Django注册:覆盖默认字段
from django import forms
from django.contrib.auth.models import User
class MyRegistrationForm(RegistrationForm):
class Meta:
model = User
fields = ('username', 'email', 'password1', 'password2')
widgets = {
'username': forms.TextInput(
attrs={'placeholder': 'hasdsa', 'class': 'form-control'}),
'email': forms.EmailInput(
attrs={'placeholder': 'hasdsa', 'class': 'form-control'}),
'password1': forms.PasswordInput(
attrs={'placeholder': 'hasdsa', 'class': 'form-control'}),
'password2': forms.PasswordInput(
attrs={'placeholder': 'hasdsa', 'class': 'form-control'}),
}
我设置的元级以这种方式,因为模型User
和领域username, email, password1, password2
是UserCreationForm
的相同属性。此代码住一个名为账户/ forms.py模块中,并从账户/ urls.py这样直接调用:
from django.conf.urls import include, url
from registration.backends.hmac import views
from accounts.forms import MyRegistrationForm
urlpatterns = [
url(r'^register/$', views.RegistrationView.as_view(form_class=MyRegistrationForm), name='registration_register'),
url(r'', include('registration.backends.hmac.urls')),
]
目的这里覆盖的输入域的属性使用窗口小部件添加属性,如class
或placeholder
或更改表格的labels
或添加error_messages
等。
正如在Django注册docs中解释的那样,您只需将您的自定义表单传递给RegistrationView
的form_class
参数即可。 完成。它不起作用,我不知道为什么。
正如你在截图中看到,DDT(Django的调试工具栏)报告的形式和所有的可用数据从那里字段。 {{ form.as_p }}
标记的输出返回此结果:
<form method="post" action=".">
<input type='hidden' name='csrfmiddlewaretoken' value='dNeT0R1JPIBtsrGCbcyPQjPLDAW7P7qb' />
<p><label for="id_username">Username:</label> <input class="form-control" id="id_username" maxlength="30" name="username" placeholder="hasdsa" type="text" /> <span class="helptext">Required. 30 characters or fewer. Letters, digits and @/./+/-/_ only.</span></p>
<p><label for="id_email">Email:</label> <input id="id_email" name="email" type="email" /> <span class="helptext">email address</span></p>
<p><label for="id_password1">Password:</label> <input id="id_password1" name="password1" type="password" /></p>
<p><label for="id_password2">Password confirmation:</label> <input id="id_password2" name="password2" type="password" /> <span class="helptext">Enter the same password as before, for verification.</span></p>
<input type="submit" value="Submit" />
</form>
并且错误来自那里。正如你所看到的,只有username
字段被更改。您可以在小部件中看到覆盖的属性class
和placeholder
。但所有其他领域仍然是一样的。只是一个问题:为什么?
相反设置的元级的模型和字段属性在上面报道的方式,我试着用:
class MyRegistrationForm(RegistrationForm):
class Meta(RegistrationForm.Meta):
widgets = { ... }
我们并不需要改变这些属性,我们只在小部件兴趣,但结果是一样的,它不起作用。
我也想知道在项目中更改所有窗体的小部件的最佳方式是什么。以这种方式覆盖每个表单?使用模板标签并过滤每个表单域?使用中间件?如果您使用像引导程序这样的框架,可能您希望为每个输入字段设置属性class="form-control"
。达到此目的的最佳方法是什么?
感谢您的时间和支持。