首页 > 解决方案 > (Django)如何制作这个注册模型和注册视图?

问题描述

我一直在尝试模仿 Instagram 注册,它需要“电话”或“电子邮件”之一。所附图片显示了哪些要求

this_is_what_I_am_creating

以下是我创建的“帐户”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 区分电话和电子邮件并将其放入正确的模型中?

标签: pythondjangoinstagram

解决方案


您可以首先使用 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


推荐阅读