![](/img/trans.png)
[英]Windows 10 python.exe neither runs nor gives error in command line
[英]Django UserCreationForm neither gives error message nor registering user
我是python Django的初學者。 並嘗試在教程的幫助下構建發布文章的網站。 我陷入了UserCreationForm。 我已經使用UserCreationForm創建了一個表單,但是在提交表單時,既無法提交表單,也無法在頁面上收到任何錯誤消息。
我的views.py代碼
from django.shortcuts import render_to_response
from django.contrib.auth import authenticate
from django.http import HttpResponseRedirect
from django.contrib import auth
from django.template.context_processors import csrf
from django.contrib.auth.forms import UserCreationForm
def register_user(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('/accounts/register_success')
args = {}
args.update(csrf(request))
args['form'] = UserCreationForm()
print args
return render_to_response('register.html', args)
def register_success(request):
return render_to_response('register_success.html')
register.html
{% extends "base.html" %}
{% block content %}
<h2>Register</h2>
<form action="/accounts/register/" method="post"> {% csrf_token %}
{{form}}
<input type="submit" value="Register"/>
</form>
{% endblock %}
register_success.html
{% extends "base.hml" %}
{% block content %}
<h2>You have registered!</h2>
<p>Click <a href="/accounts/login/">Here</a> to login again</p>
{% endblock %}
問題在於您總是在創建一個空白表格。
args['form'] = UserCreationForm()
這意味着當表單無效時,您不會看到POST請求的任何錯誤。
相反,您應該只為GET請求創建空白表格。
from django.shortcuts import render
def register_user(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('/accounts/register_success')
else:
form = UserCreationForm()
args = {'form': form}
return render(request, 'register.html', args)
請注意,我已通過使用render
而不是過時的render_to_response
簡化了視圖。 這意味着您不需要手動處理csrf。
您可以使用Django Generic Views (特別是CreateView),它將使您的生活更加輕松。 您可以這樣使用它:
from django.views.generic import CreateView
class CreateUserView(CreateView):
template_name = 'register.html'
form_class = UserCreationForm
success_url = '/accounts/register_success'
將此添加到您的urls.py
,您就可以開始了:
from mysite.views import CreateUserView
# add this url pattern
url(r'^sign_up/$', CreateUserView.as_view(), name='signup'),
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.