用django写一个登录注册界面
时间: 2023-05-28 22:03:06 浏览: 178
以下是一个简单的登录注册界面的django代码示例:
1. 创建django项目
首先,创建一个django项目并命名为“MyProject”:
```
django-admin startproject MyProject
```
接着,创建一个名为“accounts”的django应用程序:
```
cd MyProject
python manage.py startapp accounts
```
2. 创建模型
在“accounts/models.py”文件中添加一个“User”模型:
```
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager
class MyUserManager(BaseUserManager):
def create_user(self, email, password=None):
if not email:
raise ValueError('Users must have an email address')
user = self.model(
email=self.normalize_email(email),
)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, password):
user = self.create_user(
email=email,
password=password,
)
user.is_admin = True
user.save(using=self._db)
return user
class User(AbstractBaseUser):
email = models.EmailField(
verbose_name='email address',
max_length=255,
unique=True,
)
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
objects = MyUserManager()
USERNAME_FIELD = 'email'
def __str__(self):
return self.email
def has_perm(self, perm, obj=None):
return True
def has_module_perms(self, app_label):
return True
@property
def is_staff(self):
return self.is_admin
```
上述代码定义了一个“User”模型,该模型可以用电子邮件和密码进行身份验证。
3. 创建视图
在“accounts/views.py”文件中,添加以下视图:
```
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login, logout
from .forms import UserForm
def register(request):
if request.method == 'POST':
form = UserForm(request.POST)
if form.is_valid():
form.save()
email = form.cleaned_data['email']
password = form.cleaned_data['password1']
user = authenticate(request, email=email, password=password)
if user is not None:
login(request, user)
return redirect('home')
else:
form = UserForm()
return render(request, 'register.html', {'form': form})
def user_login(request):
if request.method == 'POST':
email = request.POST.get('email')
password = request.POST.get('password')
user = authenticate(request, email=email, password=password)
if user is not None:
login(request, user)
return redirect('home')
return render(request, 'login.html')
def user_logout(request):
logout(request)
return redirect('home')
```
上述代码包含了三个视图:注册、登录和注销。其中,注册视图中使用了自定义表单“UserForm”,该表单用于收集新用户的电子邮件和密码。
4. 创建表单
在“accounts/forms.py”文件中,定义一个“UserForm”表单:
```
from django import forms
from django.contrib.auth.forms import UserCreationForm
from .models import User
class UserForm(UserCreationForm):
email = forms.EmailField(max_length=254, help_text='Required. Enter a valid email address.')
class Meta:
model = User
fields = ('email', 'password1', 'password2')
```
上述代码继承了django自带的“UserCreationForm”表单,并添加了一个电子邮件字段。
5. 创建模板
在“accounts/templates”目录下,创建以下模板:
- “base.html”:所有模板都将从该模板中继承。
- “home.html”:显示用户是否已登录。
- “login.html”:显示登录表单。
- “register.html”:显示注册表单。
以下是模板代码:
“base.html”:
```
{% load static %}
<!DOCTYPE html>
<html>
<head>
<title>{% block title %}{% endblock %}</title>
<link rel="stylesheet" href="{% static 'css/style.css' %}">
</head>
<body>
<div id="header">
{% if user.is_authenticated %}
<a href="{% url 'logout' %}">Logout</a>
{% else %}
<a href="{% url 'login' %}">Login</a> / <a href="{% url 'register' %}">Register</a>
{% endif %}
</div>
<div id="content">
{% block content %}
{% endblock %}
</div>
</body>
</html>
```
“home.html”:
```
{% extends 'base.html' %}
{% block title %}Home{% endblock %}
{% block content %}
{% if user.is_authenticated %}
<p>Welcome, {{ user.email }}!</p>
{% else %}
<p>You are not logged in.</p>
{% endif %}
{% endblock %}
```
“login.html”:
```
{% extends 'base.html' %}
{% block title %}Login{% endblock %}
{% block content %}
<h2>Login</h2>
<form method="post">
{% csrf_token %}
<div class="form-group">
<label for="email">Email address:</label>
<input type="email" name="email" required class="form-control" id="email">
</div>
<div class="form-group">
<label for="password">Password:</label>
<input type="password" name="password" required class="form-control" id="password">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
{% endblock %}
```
“register.html”:
```
{% extends 'base.html' %}
{% block title %}Register{% endblock %}
{% block content %}
<h2>Register</h2>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="btn btn-primary">Submit</button>
</form>
{% endblock %}
```
6. 配置URL
在“MyProject/urls.py”文件中,添加以下URL:
```
from django.urls import path
from accounts.views import register, user_login, user_logout
urlpatterns = [
path('register/', register, name='register'),
path('login/', user_login, name='login'),
path('logout/', user_logout, name='logout'),
]
```
7. 运行项目
现在可以运行django项目并在浏览器中访问登录注册界面:
```
python manage.py runserver
```
在浏览器中访问“http://127.0.0.1:8000/register/”即可打开注册页面,访问“http://127.0.0.1:8000/login/”即可打开登录页面。
阅读全文