我有一个简单的用户注册表单(在forms.py中):
from django.contrib.auth.models import User
class UserForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput
validators=[MinLengthValidator(6)])
password_repeat = forms.CharField(widget=forms.PasswordInput)
class Meta:
model = User
fields = ['username', 'password','password_repeat']
如果有人试图输入内容并且验证失败,我希望再次呈现相同的表单,但应清除所有字段。目前我的观点看起来像这样(在views.py中):
def signup(request):
form = UserForm(request.POST or None)
if form.is_valid():
user = form.save(commit=False)
username = form.cleaned_data['username']
password = form.cleaned_data['password']
password_repeat = form.cleaned_data['password-repeat']
user.set_password(password)
user.save()
user = auth.authenticate(username=username, password=password)
if user is not None and user.is_active:
auth.login(request, user)
return redirect('/')
return render(request, 'signup.html', {'form': form})
问题是form.fields['username']
字段仍然包含输入的用户名,因此传递给渲染。
我一直在寻找解决方案,但找不到它。我的猜测是该解决方案与我似乎无法获得的clean()
方法有关。
答案 0 :(得分:2)
这是一个奇怪的事情 - 它与人们通常会问的问题相反,因为大多数人都希望保留字段并显示错误。
但是,如果你真的想要清除表单,你应该只是实例化一个新表单。
if form.is_valid():
...
else:
form = UserForm()
return render(request, 'signup.html', {'form': form})
答案 1 :(得分:0)
要在保留所有表单验证错误的同时始终清除特定表单字段,您可以创建一个自定义输入窗口小部件,该窗口小部件始终“忘记”它的旧值。例如:
weatha-picka.ejs
参考:django.forms.Widget.get_context
行为
假设我们在这样的视图中使用<html>
<head>
<title>EJS template</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<!-- Use ejs template and html here -->
</body>
</html>
:
from django import forms
class NonstickyTextInput(forms.TextInput):
'''Custom text input widget that's "non-sticky"
(i.e. does not remember submitted values).
'''
def get_context(self, name, value, attrs):
value = None # Clear the submitted value.
return super().get_context(name, value, attrs)
class MyForm(forms.Form):
username = forms.CharField(widget=NonstickyTextInput())
# ...
当表单遇到任何验证错误并重新显示该表单时,所有常见的验证错误消息都将显示在表单上,但是显示的MyForm
表单字段将为空白。