(Django) 如何制作这个注册模型和注册视图?

(Django) How do I make this signup model and signupview?

我一直在尝试模拟采用 'phone' 或 'email' 之一的 Instagram 注册。所附图片显示了要求

以下是我创建的 'account' Django 应用的文件:

models.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

views.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)

由于用户输入了 phone 号码或电子邮件,我如何让 django 区分 phone 和电子邮件并将其放入正确的模型中?

您可以先使用 validate_email 来验证输入是否为电子邮件,如果不是则尝试验证 phone 样式。

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