我正在尝试制作自定义用户注册表单
这是我的views.py代码
from django.shortcuts import render, redirect
from django.views.generic import TemplateView
from .forms import RegistrationForm
# Create your views here.
def register(request):
if request.POST:
form = RegistrationForm(request.POST)
if form.is_valid():
form.save()
return redirect("profile/")
else:
form = RegistrationForm()
context = {'form': form}
return render(request, 'accounts/registration.html', context)
这是我的forms.py代码
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
class RegistrationForm(UserCreationForm):
email = forms.EmailField(required=True)
class Meta:
model = User
fields = [
'username',
'first_name',
'last_name',
'email',
'password1',
'password2',
]
def save(self, commit=True):
user = super(RegistrationForm, self).save(commit=False)
user.first_name = self.cleaned_data['first_name']
user.last_name = self.cleaned_data['last_name']
user.email = self.cleaned_data['email']
if commit:
user.save()
return user
当我运行此代码时,它正在运行,但当我尝试注册用户时,它正在返回
ValueError at /accounts/registration/
The view accounts.views.register didn't return an HttpResponse object. It
returned None instead.
这里的帐户是我的Django应用程序的名称
答案 0 :(得分:0)
在您的views.py
中,如果请求的类型为redirect()
且,则表单有效,您只返回POST
;或者如果您收到任何其他请求类型。您没有处理请求类型为POST
且表单无效的情况。通过扩展语句可以很容易地解决这个问题:
def register(request):
# Always use request.method to check whether it's a POST or GET request
if not request.method == 'POST':
form = RegistrationForm()
context = {'form': form}
return render(request, 'accounts/registration.html', context)
form = RegistrationForm(request.POST)
if not form.is_valid():
# Handle the case in which the form is invalid here.
# Make sure you return redirect() or render() here.
# Now we're in the case in which the form _is_ valid
form.save()
return redirect("profile/")
我还使你的代码更加pythonic并降低了if语句的复杂性。请注意,始终使用request.method
来验证传入请求的类型。在任何情况下,您的视图应始终返回redirect()
或render()
对象,以避免问题中引用的错误。
答案 1 :(得分:0)
将视图的最后两行移回一个缩进级别,以便它们在所有情况下都可以执行。