我已经创建了一个用户注册表单,每件事看起来都不错,但是当我尝试注册新用户时,它将带回相同的表单,同时将其重定向到主页。另外,当我去管理员那里寻找新的注册用户时,我什么也没看到
这适用于python 3.7.3,django 2.2.3和mysql 5.7.26。我尝试检查并重新检查每件事似乎都还可以,但仍然无法实现我想要的目的
forms.py
class NewUserForm(UserCreationForm):
email = forms.EmailField(required=True)
class Meta:
model = User
fields = ("username","email","password1","password2")
views.py
def register(request):
if request.method == "POST":
user_form = UserCreationForm(request.POST)
if user_form.is_valid():
user = user_form.save()
username = user_form.cleaned_data.get("username")
raw_password = user_form.cleaned_data.get("password1")
user = authenticate(username=username, password=raw_password)
login(request, user)
return redirect("loststuffapp:IndexView")
else:
for msg in user_form.error_messages:
print(user_form.error_messages[msg])
else:
user_form = UserCreationForm
return render(
request,
"loststuffapp/register.html",
context={"user_form":user_form}
)
register.html
{% extends "loststuffapp/base.html" %}
{% block content %}
<form method="POST">
{% csrf_token %}
{{user_form.as_p}}
<button type="submit" style="background-color:
yellow">Register</button>>
If you already have an account, <a href="/Register">login</a> instead
{% endblock %}
答案 0 :(得分:0)
您必须先验证用户身份,然后才能登录。请参见以下示例,取自https://simpleisbetterthancomplex.com/tutorial/2017/02/18/how-to-create-user-sign-up-view.html
# Taken from https://simpleisbetterthancomplex.com/tutorial/2017/02/18/how-to-create-user-sign-up-view.html
from django.contrib.auth import login, authenticate
from django.contrib.auth.forms import UserCreationForm
from django.shortcuts import render, redirect
def signup(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
raw_password = form.cleaned_data.get('password1')
user = authenticate(username=username, password=raw_password)
login(request, user)
return redirect('home')
else:
form = UserCreationForm()
return render(request, 'signup.html', {'form': form})