这是我的forms.py,
class RegistrationForm(UserCreationForm):
class Meta:
model = User
fields = [ 'username', 'first_name', 'password1', 'password2']
def save(self, commit=True):
user = super(RegistrationForm, self).save(commit=False)
user.first_name = self.cleaned_data['first_name']
if commit:
user.save()
return user
在views.py中,
def register(request):
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
form.save()
username = request.POST.get('username')
password = request.POST.get('password1')
user = authenticate(username=username, password=password)
login(request, user)
return redirect(reverse('accounts:profile'))
else:
form = RegistrationForm()
return render(request, 'accounts/reg_form.html', {'form': form})
现在,如果我使用相同的用户名,则会引发错误,显示“视图accounts.views.register未返回HttpResponse对象。它返回None。”我该如何解决这个问题?
谢谢你:)
答案 0 :(得分:1)
默认情况下,Django表单会为您执行此操作。
您不需要特定于此。
因为django提供的默认User
模型不会使用重复的用户名。
可能是一些缩进问题
def register(request):
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
form.save()
. . . .
else:
form = RegistrationForm()
return render(request, 'accounts/reg_form.html', {'form': form})
#^^^^^Indentation here take return statement outside else