类型错误:__init__() 有一个意外的关键字参数"小部件"



我写forms.py时出错

from django.contrib.auth.forms import AuthenticationForm, UserCreationForm, UsernameField
class SignupForm(UserCreationForm):
password1= forms.CharField(label='password',widget=forms.PasswordInput(attrs={'class':'form-control'}))
password2= forms.CharField(label='Confirm password(again)',widget=forms.PasswordInput(attrs={'class':'form-control'}))

服务器说:

username= UsernameField(label='username',widgets=forms.TextInput(attrs={'autofocus':True,'class':'form-control bg-success'}))
File "C:UsersITSAppDataLocalProgramsPythonPython39libsite-packagesdjangoformsfields.py", line 216, in __init__
super().__init__(**kwargs)
TypeError: __init__() got an unexpected keyword argument 'widgets'

但是当我在meta类中写widgets时:

class LoginForm(AuthenticationForm):
username= UsernameField(label='username')
password= forms.CharField(label=('password'),strip=False)
class Meta:
widgets={
'username':forms.TextInput(attrs={'autofocus':True,'class':'form-control'}),
'password':forms.PasswordInput(attrs={'autocomplete':'current-password','class':'form-control'}),
}

服务器完全工作,但是表单控件类不在HTML页面中。

HTML代码:

{% extends 'base.html' %}
{% block content %}
<div class="col-sm-10">
<h3 class="text-white my-5"> Login Page</h3>
<form action="" method="post" novalidate>
{% csrf_token %}
{% for fm in form %}
<div class="">
{{fm.label_tag}}{{fm}}<small class="text-warning">{{fm.errors| striptags}}</small>
</div>
{% endfor %}<br>
<input type="submit" class=" btn btn-primary" value="Login">
{% if form.non_field_errors %}
{% for error in form.non_field_errors %}<br>
<p class="alert alert-danger my-3">{{ error}}</p>

{% endfor %}
{% endif %}
</form>
</div>
{% endblock  %}

请帮我一下。

在表单中错误地使用了widgets而不是widget试试下面的修改:-

username= UsernameField(label='username', widget=forms.TextInput(attrs={'autofocus':True,'class':'form-control bg-success'}))

在这里定义:- https://github.com/django/django/blob/main/django/contrib/auth/forms.py#L66