总结:
1.在models.py免注册User;2.在forms.py新增UserForm;3.views.py需要写入register视图;4.编写register.html;5.添加urls;
1. models.py采用默认的user models,不用另外定义 class User。
# 采用默认的user models,不用另外定义 class User
2.forms.py需要用UserForm(forms.ModelForm)才能显示全部user字段,用class UserForm(forms.Form)只能显示密码。
class UserForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput())
class Meta:
model = User
fields = ('username','email','password')
Form不应该写成如下:
class UserForm(forms.Form):
password = forms.CharField(widget=forms.PasswordInput())
class Meta:
model = User
fields = ('username','email','password')
这是错误的界面
3. views.py需要写入register视图。
# 建立user注册界面
# 建立user注册界面
def register(request):
registered = False
if request.method == 'POST':
user_form = UserForm(data=request.POST)
if user_form.is_valid():
user = user_form.save()
user.is_staff = True
user.set_password(user.password)
user.save()
registered = True
else:
print(user_form.errors)
else:
user_form = UserForm()
return render(request,'myclass/register.html',{'user_form':user_form,'registered':registered})
以下是个错误,因为字典写反了。
以下是个错误,因为字典写反了。
return render(request,'myclass/register.html',{user_form:'user_form','registered':registered})
4.register.html
这个模板使用视图中的 registered 变量判断注册是否成功。registered 的值为 False 时,显示注册表单;否则,显示成功注册消息。
<html>
<head>
<title>Register</title>
</head>
<body>
<h1>Register for yourself</h1>
{% if registered %}
thank you for your registering.
<a href="{% url 'index' %}">Return to index.</a>
{% else %}
<form action="" method="POST">
{% csrf_token %}
{{ user_form.as_p }}
<input type="submit" value="Submit">
</form>
{% endif %}
</body>
</html>
5.添加urls
urlpatterns = [
........
path('register/', views.register, name='register'),
]
6.表单提交成功的界面如下:
7.如何确保输入的密码符合要求呢?user.set_password(user.password)
假设你发现密码是无法显示的,就需要在views中增加两行代码。 user.set_password(user.password)
user.save()
# 建立user注册界面
def register(request):
registered = False
if request.method == 'POST':
user_form = UserForm(data=request.POST)
if user_form.is_valid():
user = user_form.save()
user.is_staff = True
user.set_password(user.password)
user.save()
registered = True
else:
print(user_form.errors)
else:
user_form = UserForm()
return render(request,'myclass/register.html',{'user_form':user_form,'registered':registered})
password才会显示正常。
8.如何避免手动到admin后台设定Staff status呢?user.is_staff = True
如果用户状态是Active和Staff status,那么博客系统的前台后台都能登录。如果用户状态只是Active,那么只能登录系统的前台系统,不能登录admin后台
在views.py中输入代码user.is_staff = True
# 建立user注册界面
def register(request):
registered = False
if request.method == 'POST':
user_form = UserForm(data=request.POST)
if user_form.is_valid():
user = user_form.save()
user.is_staff = True
user.set_password(user.password)
user.save()
registered = True
else:
print(user_form.errors)
else:
user_form = UserForm()
return render(request,'myclass/register.html',{'user_form':user_form,'registered':registered})