I have been trying to emulate Instagram signup which takes either one of 'phone' or 'email'. The image attached shows what requirements are
Below are the files for my 'account' Django app that I created:
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)
Since the user put in either phone number or email, how do I make django to distinguish between the phone and email and put it in the correct model?
You can use validate_email to validate input is email or not at first, if not then try to validate phone style.
from django.core.validators import validate_email
try:
validate_email(data['email_or_phone'])
print('input is email')
except ValidationError:
print('do phone validate')
doc: https://docs.djangoproject.com/en/3.0/ref/validators/#validate-email
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.