django写一份前后交互的登录注册页面
时间: 2024-09-27 22:07:35 浏览: 36
基于Django和vue3的电影推荐系统(附完整文档和图文说明)
Django是一个流行的Python Web框架,可以轻松创建复杂的Web应用。要在Django中编写前后端交互的登录和注册页面,我们通常会使用视图(Views)处理业务逻辑,模板(Templates)渲染用户界面,并结合表单(Form)验证用户输入。
1. **设置项目和应用**:
首先,确保你已经安装了Django,然后创建一个新的项目和应用,例如`myproject`和`authapp`。
2. **模型(Model)**:
在`models.py`文件中,如果还没有,创建User模型关联到Django内置的AbstractUser模型,用于存储用户信息:
```python
from django.contrib.auth.models import AbstractUser
class CustomUser(AbstractUser):
pass
```
3. **视图(Views)**:
在`views.py`中,编写视图函数来处理登录和注册请求。比如,`login_view`和`register_view`:
```python
from django.shortcuts import render, redirect
from django.contrib.auth import login, authenticate, logout
from .forms import LoginForm, RegisterForm
def login_view(request):
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
user = authenticate(request, username=form.cleaned_data['username'], password=form.cleaned_data['password'])
if user is not None:
login(request, user)
return redirect('home') # 跳转到主页
else:
form = LoginForm()
return render(request, 'login.html', {'form': form})
def register_view(request):
if request.method == 'POST':
form = RegisterForm(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 = RegisterForm()
return render(request, 'register.html', {'form': form})
```
4. **URL配置**:
在`urls.py`中,为这两个视图添加URL规则:
```python
from django.urls import path
from . import views
urlpatterns = [
path('login/', views.login_view, name='login'),
path('register/', views.register_view, name='register'),
]
```
5. **模板(HTML)**:
在`templates/authapp`目录下,创建`login.html`和`register.html`,分别用于展示登录和注册表单,使用Django模板语法:
```html
<!-- login.html -->
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">登录</button>
</form>
<!-- register.html -->
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">注册</button>
</form>
```
6. **表单(Form)**:
在`forms.py`中,定义表单类:
```python
from django import forms
from django.contrib.auth.forms import UserCreationForm
class LoginForm(forms.Form):
username = forms.CharField(label='用户名')
password = forms.CharField(widget=forms.PasswordInput)
class RegisterForm(UserCreationForm):
class Meta:
model = CustomUser
fields = ['username', 'email', 'password1', 'password2']
```
7. **静态文件和前端**:
使用HTML/CSS/JavaScript构建前端,可以使用Bootstrap或其他库简化样式和交互。
阅读全文