所以我刚创建了一个表单并不断收到此错误,为什么?我在检查表单是否有效后正确使用了Cleaned_data,对吗?
这是我的forms.py:
class UserForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput)
username = forms.CharField(max_length=10)
email = forms.EmailField()
class Meta:
model = User
fields = ['username', 'email', 'password']
这是我的views.py:
class UserFormView(View):
form_class = UserForm
template_name = 'Home/index.html'
def get(self, request):
form = self.form_class(None)
return render(request, self.template_name, {'form': form})
def post(self, request):
form = self.form_class(request.POST)
if form.is_valid():
user = form.save(commit=False)
username = form.Cleaned_data['username']
password = form.Cleaned_data['password']
user.set_password(password)
user.save()
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
return redirect('Home:Dashboard')
return render(request, self.template_name, {'form': form})
我的urls.py:
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^register$', views.UserFormView.as_view(), name='register'),]
和表单位置:
<form action="/register" method="post">
{% csrf_token %}
<ul class="contactList">
<li id="username1" class="contact">{{ form.username }}</li>
<li id="email1" class="contact">{{ form.email }}</li>
<li id="password1" class="contact">{{ form.password }}</li>
</ul>
<input type="submit" value="Submit">
</form>
关于这个问题还有其他主题,但我无法从中得到任何帮助,因为大多数人都没有包含if form.is_valid(),但在我的情况下我做了。
答案 0 :(得分:1)
使用form.cleaned_data.get('username')
代替form.Cleaned_data
修改强>
使用FormView
from django.views.generic.edit import FormView
class UserFormView(FormView):
form_class = UserForm
template_name = 'Home/index.html'
def form_valid(self, form):
user = form.save(commit=False)
username = form.cleaned_data.get('username')
...
get_form_class
返回表单的类,即UserForm
。你需要的是那个类的一个对象。该类没有任何属性cleaned_data
。