use*_*875 6 forms django django-views django-authentication django-registration
这是我的看法:
def main_page(request):
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
user = User.objects.create_user(
username=form.clean_data['username'],
password=form.clean_data['password1'],
email=form.clean_data['email']
)
return HttpResponseRedirect('/')
else:
form = RegistrationForm()
variables = {
'form': form
}
return render(request, 'main_page.html', variables)
Run Code Online (Sandbox Code Playgroud)
这是我的main_page.html:
{% if form.errors %}
<p>NOT VALID</p>
{% for errors in form.errors %}
{{ errors }}
{% endfor %}
{% endif %}
<form method="post" action="/">{% csrf_token %}
<p><label for="id_username">Username:</label>{{ form.username }}</p>
<p><label for="id_email">Email Address:</label>{{ form.email }}</p>
<p><label for="id_password">Password:</label>{{ form.password1 }}</p>
<p><label for="id_retypePassword">Retype Password:</label>{{ form.password2 }}</p>
<input type="hidden" name="next" />
<input type="submit" value="Register" />
</form>
Run Code Online (Sandbox Code Playgroud)
当我转到使用main_page视图的url时,它只显示表单.当我提交包含错误的表单(包含空白字段且没有正确的电子邮件地址)时,它只会将我重定向到同一页面,并且不会显示任何错误.它甚至没有说"无效".
当我改变
{% if form.errors %}
Run Code Online (Sandbox Code Playgroud)
至
{% if not form.is_valid %}
Run Code Online (Sandbox Code Playgroud)
它总是说"无效"(即使它是第一次进入网址,即使我还没有提交任何内容).
这是我的RegistrationForm:
from django import forms
import re
from django.contrib.auth.models import User
from django.core.exceptions import ObjectDoesNotExist
class RegistrationForm(forms.Form):
username = forms.CharField(label='Username', max_length=30)
email = forms.EmailField(label='Email')
password1 = forms.CharField(label='Password', widget=forms.PasswordInput())
password2 = forms.CharField(label='Password (Again)', widget=forms.PasswordInput())
def clean_password2(self):
if 'password1' in self.cleaned_data:
password1 = self.cleaned_data['password1']
password2 = self.cleaned_data['password2']
if password1 == password2:
return password2
raise forms.ValidationError('Passwords do not match.')
def clean_username(self):
username = self.cleaned_data['username']
if not re.search(r'^\w+$', username): #checks if all the characters in username are in the regex. If they aren't, it returns None
raise forms.ValidationError('Username can only contain alphanumeric characters and the underscore.')
try:
User.objects.get(username=username) #this raises an ObjectDoesNotExist exception if it doesn't find a user with that username
except ObjectDoesNotExist:
return username #if username doesn't exist, this is good. We can create the username
raise forms.ValidationError('Username is already taken.')
Run Code Online (Sandbox Code Playgroud)
它正在重定向您,因为HttpResponseRedirect如果方法是POST,您总是返回,即使表单不是vaild.试试这个:
def main_page(request):
form = RegistrationForm()
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
user = User.objects.create_user(
username=form.clean_data['username'],
password=form.clean_data['password1'],
email=form.clean_data['email']
)
return HttpResponseRedirect('/')
variables = {
'form': form
}
return render(request, 'main_page.html', variables)
Run Code Online (Sandbox Code Playgroud)
这样,is_valid调用的表单实例就会传递给模板,并且有机会显示错误.仅当表单有效时,才会重定向用户.如果您想要花哨,请在重定向之前使用消息框架添加消息.
如果你想要它更简洁一点:
def main_page(request):
form = RegistrationForm(request.POST or None)
if form.is_valid():
user = User.objects.create_user(
username=form.clean_data['username'],
password=form.clean_data['password1'],
email=form.clean_data['email']
)
return HttpResponseRedirect('/')
variables = {
'form': form
}
return render(request, 'main_page.html', variables)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
18625 次 |
| 最近记录: |