有代码吗
时间: 2024-02-16 11:00:39 浏览: 75
代码
以下是一个使用Django框架实现的用户登录和注册系统的示例代码:
首先,在Django的settings.py文件中添加以下配置:
```python
# settings.py
# 加密密钥
SECRET_KEY = 'your-secret-key'
# 注册app
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'account', # 注册的app
]
# 数据库设置
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'your-database-name',
'USER': 'your-database-user',
'PASSWORD': 'your-database-password',
'HOST': 'your-database-host',
'PORT': 'your-database-port',
}
}
# 认证系统设置
AUTH_USER_MODEL = 'account.User'
LOGIN_URL = '/login/'
LOGIN_REDIRECT_URL = '/'
```
接下来,创建一个account app,并在models.py文件中定义用户模型和用户管理器:
```python
# models.py
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager
class UserManager(BaseUserManager):
def create_user(self, email, username, password=None):
if not email:
raise ValueError('Users must have an email address')
user = self.model(
email=self.normalize_email(email),
username=username,
)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, username, password):
user = self.create_user(
email=self.normalize_email(email),
username=username,
password=password,
)
user.is_admin = True
user.save(using=self._db)
return user
class User(AbstractBaseUser):
email = models.EmailField(max_length=255, unique=True)
username = models.CharField(max_length=30, unique=True)
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
objects = UserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username']
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
```
接下来,在views.py文件中编写登录和注册的视图函数:
```python
# views.py
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login
from .forms import RegistrationForm
def register(request):
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
form.save()
return redirect('/')
else:
form = RegistrationForm()
return render(request, 'account/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('/')
else:
return render(request, 'account/login.html', {'error': 'Invalid email or password'})
else:
return render(request, 'account/login.html')
```
最后,在forms.py文件中编写注册表单的验证逻辑:
```python
# forms.py
from django import forms
from django.contrib.auth.forms import UserCreationForm
from .models import User
class RegistrationForm(UserCreationForm):
email = forms.EmailField(required=True)
class Meta:
model = User
fields = ('email', 'username', 'password1', 'password2')
def save(self, commit=True):
user = super(RegistrationForm, self).save(commit=False)
user.email = self.cleaned_data['email']
if commit:
user.save()
return user
```
这样,一个基本的用户登录和注册系统就完成了。您可以按照自己的需求进行修改和扩展。
阅读全文