我使用的是Django 1.9.8,並且在註冊用戶時驗證表單有些麻煩。如果存在驗證錯誤,則重定向回到表單就是不正確的url。註冊網址是localhost:8000/register
。當發現錯誤(無論如何,我認爲這就是發生了什麼),頁面被重定向到localhost:8000/register/register
。我做了什麼錯誤導致重定向爲url添加了一個額外的register
參數?Django表單驗證沒有重定向到正確的網址
#authorization/views.py
class RegisterViewSet(viewsets.ViewSet):
#GET requests
def register(self,request):
return render(request, 'authorization/register.html', {'form': RegisterForm})
#POST requests
def create(self,request):
form = RegisterForm(request.POST)
if form.is_valid():
username = request.POST['username']
email = request.POST['email']
password = request.POST['password']
user = User.objects.create_user(username,email,password)
user.save()
return HttpResponseRedirect('/users') #show list of users after saving
else:
#return to the form for the user to fix errors & continue registering
return render(request, 'authorization/register.html', {'form': RegisterForm})
這裏的RegisterForm內容
#authorization/forms.py
class RegisterForm(AuthenticationForm):
username = forms.CharField(label="Username", max_length=30,
widget=forms.TextInput(attrs={'class': 'form-control', 'name': 'username'}))
email = forms.CharField(label="Email", max_length=30,
widget=forms.TextInput(attrs={'class': 'form-control', 'name': 'email'}))
password = forms.CharField(label="Password", max_length=30,
widget=forms.TextInput(attrs={'class': 'form-control', 'name': 'password', 'type' : 'password'}))
repassword = forms.CharField(label="RePassword", max_length=30,
widget=forms.TextInput(attrs={'class': 'form-control', 'name': 'repassword', 'type' : 'password'}))
def clean_password(self):
password1 = self.cleaned_data.get('password')
password2 = self.cleaned_data.get('repassword')
if password1 and password1 != password2:
raise forms.ValidationError("Passwords don't match")
return self.cleaned_data
我不知道這是否是相關的,但這裏是我的urls.py
#authorization/urls.py
urlpatterns = [
url(r'^$', views.home, name='home'),
url(r'^register/', views.RegisterViewSet.as_view({'get' : 'register', 'post' : 'create'})),
]
我加入之前測試的創建方法表單驗證部分,它已經成功地保存了用戶,所以我知道它至少在這一點上起作用。
編輯 - 添加表格內容
{% if form.errors %}
{% for field in form %}
{% for error in field.errors %}
<div class="alert alert-error">
<strong>{{ error|escape }}</strong>
</div>
{% endfor %}
{% endfor %}
{% endif %}
<form method="post" action="register" id = "RegisterForm">
{% csrf_token %}
<p class="bs-component">
<table>
<tr>
<td>{{ form.username.label_tag }}</td>
<td>{{ form.username }}</td>
</tr>
<tr>
<td>{{ form.email.label_tag }}</td>
<td>{{ form.email }}</td>
</tr>
<tr>
<td>{{ form.password.label_tag }}</td>
<td>{{ form.password }}</td>
</tr>
<tr>
<td>{{ form.repassword.label_tag }}</td>
<td>{{ form.repassword }}</td>
</tr>
</table>
</p>
<p class="bs-component">
<center>
<input class="btn btn-success btn-sm" type="submit" value="Register" />
</center>
</p>
<input type="hidden" name="next" value="{{ next }}" />
</form>
您可以顯示'寄存器.html'模板? – knbk
@knbk添加了表格 – user1852176