python - (Django)如何制作这个注册模型和注册视图?
问题描述
我一直在尝试模仿 Instagram 注册,它需要“电话”或“电子邮件”之一。所附图片显示了哪些要求
以下是我创建的“帐户”Django 应用程序的文件:
模型.py
from django.db import models
class Account(models.Model):
email = models.EmailField(max_length = 254)
password = models.CharField(max_length=700)
fullname = models.CharField(max_length=200)
username = models.CharField(max_length=200)
phone = models.CharField(max_length=100)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
db_table = 'accounts'
def __str__(self):
return self.username + " " + self.fullname
视图.py
import json
import bcrypt
import jwt
from django.views import View
from django.http import HttpResponse, JsonResponse
from django.db.models import Q
from .models import Account
class SignUpView(View):
def post(self, request):
data = json.loads(request.body)
try:
if Account.objects.filter(email=data['email']).exists():
return JsonResponse({"message": "ALREADY EXIST"}, status=409)
elif Account.objects.filter(email=data['phone']).exists():
return JsonResponse({"message": "ALREADY EXIST"}, status=409)
elif Account.objects.filter(username=data['username']).exists():
return JsonResponse({"message": "ALREADY EXIST"}, status=409)
hashed_pw = bcrypt.hashpw(data['password'].encode('utf-8'),bcrypt.gensalt()).decode()
Account.objects.create(
email = data['email'],
password = hashed_pw,
fullname = data['fullname'],
username = data['username'],
phone = data['phone'],
)
return JsonResponse({"message": "SUCCESS"}, status=200)
except KeyError:
return JsonResponse({"message": "INVALID_KEYS"}, status=400)
由于用户输入了电话号码或电子邮件,我如何让 django 区分电话和电子邮件并将其放入正确的模型中?
解决方案
您可以首先使用 validate_email 来验证输入是否为电子邮件,如果不是,则尝试验证电话样式。
from django.core.validators import validate_email
try:
validate_email(data['email_or_phone'])
print('input is email')
except ValidationError:
print('do phone validate')
文档:https ://docs.djangoproject.com/en/3.0/ref/validators/#validate-email
推荐阅读
- python - 使用 boto3 创建粘合作业时指定作业类型
- php - 如何在 foreach 循环 PHP 中创建和命名复选框
- java - 超频 cpu 导致 JRE 中的致命错误
- c++ - 宏上的用户定义文字运算符
- google-sheets - 谷歌表格数据查找
- laravel - 使用服务器端数据表时在 vue.js 前端添加操作按钮
- java - 使用 POSTMAN 测试 API 时 AdapterSecurityContext 的客户端注册数据为空
- javascript - 如何在开始时使用 img 标签 src
如何在javascript源代码中动态使用带有src begin '<'c:url'>'的img标签
在 html 源代码中效果很好,但在 javascript 源代码中我不知道如何在字符串中使用 img 标签
[html]
<div> <img src="<c:url value="${contex
- android - 如何在 React Native 上集成 Android 应用事件?
- python - 分别为多个文件保存每个文件中的多个图形