django 中设置注册和登录选项,用户注册后自动存储用户信息,登录后后显示shoyye,html
时间: 2024-05-12 16:14:54 浏览: 11
在 Django 中设置注册和登录选项,可以使用 Django 自带的认证系统,也可以使用第三方库。这里以 Django 自带的认证系统为例。
首先,在 `settings.py` 中添加认证系统的配置:
```python
AUTHENTICATION_BACKENDS = [
'django.contrib.auth.backends.ModelBackend',
]
```
然后,在 `urls.py` 中添加认证系统的 URL 配置:
```python
from django.urls import path, include
urlpatterns = [
path('accounts/', include('django.contrib.auth.urls')),
]
```
接着,在 `views.py` 中编写注册和登录的视图函数:
```python
from django.shortcuts import render, redirect
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
from django.contrib.auth import login
def register(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
user = form.save()
login(request, user)
return redirect('home')
else:
form = UserCreationForm()
return render(request, 'registration/register.html', {'form': form})
def login(request):
if request.method == 'POST':
form = AuthenticationForm(request, request.POST)
if form.is_valid():
login(request, form.get_user())
return redirect('home')
else:
form = AuthenticationForm()
return render(request, 'registration/login.html', {'form': form})
```
在这里,我们使用 Django 自带的表单类 `UserCreationForm` 和 `AuthenticationForm` 分别处理注册和登录的表单数据。在表单数据验证通过后,我们调用 `login` 函数登录用户,并重定向到主页 `home`。
最后,在 `views.py` 中添加主页的视图函数:
```python
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
@login_required
def home(request):
return render(request, 'home.html')
```
在这里,我们使用 `login_required` 装饰器来保护主页视图函数,只有登录用户才能访问主页。
以上就是 Django 中设置注册和登录选项,并在登录后显示主页的流程。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)