0

I am trying to implement Sign Up page in Django using User models. In HTML page, there is an input field for email or phone number. The value I got from this field is assigned to username in Django User model and if the entered value is email, then the value is assigned to email in the User model. Otherwise value assigned to the phone in the User model. When I run the server, user can enter his details with email once. For the second time onwards, I got an error like this:

IntegrityError at /Accounts/CandidateRegister/
(1062, "Duplicate entry '' for key 'phone'")
Request Method: POST
Request URL:    http://127.0.0.1:8000/Accounts/CandidateRegister/
Django Version: 4.0.2
Exception Type: IntegrityError
Exception Value:    
(1062, "Duplicate entry '' for key 'phone'")
Exception Location: C:\job\venv\lib\site-packages\MySQLdb\connections.py, line 254, in query
Python Executable:  C:\job\venv\Scripts\python.exe
Python Version: 3.9.7
Python Path:    
['C:\\job\\jobsite',
 'C:\\Users\\Student\\AppData\\Local\\Programs\\Python\\Python39\\python39.zip',
 'C:\\Users\\Student\\AppData\\Local\\Programs\\Python\\Python39\\DLLs',
 'C:\\Users\\Student\\AppData\\Local\\Programs\\Python\\Python39\\lib',
 'C:\\Users\\Student\\AppData\\Local\\Programs\\Python\\Python39',
 'C:\\job\\venv',
 'C:\\job\\venv\\lib\\site-packages']

Similarly, when a user enter with his phone number, their details will saved to database once. After that I got an error like this:

IntegrityError at /Accounts/CandidateRegister/
(1062, "Duplicate entry '' for key 'email'")
Request Method: POST
Request URL:    http://127.0.0.1:8000/Accounts/CandidateRegister/
Django Version: 4.0.2
Exception Type: IntegrityError
Exception Value:    
(1062, "Duplicate entry '' for key 'email'")
Exception Location: C:\job\venv\lib\site-packages\MySQLdb\connections.py, line 254, in query
Python Executable:  C:\job\venv\Scripts\python.exe
Python Version: 3.9.7
Python Path:    
['C:\\job\\jobsite',
 'C:\\Users\\Student\\AppData\\Local\\Programs\\Python\\Python39\\python39.zip',
 'C:\\Users\\Student\\AppData\\Local\\Programs\\Python\\Python39\\DLLs',
 'C:\\Users\\Student\\AppData\\Local\\Programs\\Python\\Python39\\lib',
 'C:\\Users\\Student\\AppData\\Local\\Programs\\Python\\Python39',
 'C:\\job\\venv',
 'C:\\job\\venv\\lib\\site-packages']

Can anyone suggest a solution to solve this issue.

HTML code:

<form style="padding:10px 25%;" class="signup-form" id="candidate" method="POST" action="{% url 'candidateregister' %}">
                         {% csrf_token %}
                      <div class="form-row">
                        <div class="form-group col-md-6">
                          <label for="cafname" style="font: normal normal normal 16px/18px Poppins;">First name</label>
                          <input type="text" class="form-control" id="cafname" name="cafname" placeholder="Your first name" style="font-family:sans-serif;border:2px solid #d4d2d2;" required>
                        </div>
                        <div class="form-group col-md-6">
                          <label for="calname" style="font: normal normal normal 16px/18px Poppins;">Last name</label>
                          <input type="text" class="form-control" id="calname" name="calname" placeholder="Your last name" style="font-family:sans-serif;border:2px solid #d4d2d2;" required>
                        </div>
                      </div>
                      <div class="form-group">
                        <label for="caemorpn" style="font: normal normal normal 16px/18px Poppins;">Email or Phone number</label>
                        <input type="text" class="form-control" id="caemorpn" name="caemorpn" placeholder="Enter email or phone number" style="font-family:sans-serif;border:2px solid #d4d2d2;" required>
                      </div>
                      <div class="form-group">
                        <label for="capassword1" style="font: normal normal normal 16px/18px Poppins;">Password</label>
                        <input type="password" class="form-control" id="capassword1" name="capassword1" placeholder="Enter your password" style="font-family:sans-serif;border:2px solid #d4d2d2;" required>
                      </div>
                      <div class="form-group">
                        <label for="capassword2" style="font: normal normal normal 16px/18px Poppins;">Confirm Password</label>
                        <input type="password" class="form-control" id="capassword2" name="capassword2" placeholder="Confirm your password" style="font-family:sans-serif;border:2px solid #d4d2d2;" required>
                      </div>
                      <div class="form-group">
                        <div class="form-check">
                          <input class="form-check-input" type="checkbox" id="cagridCheck" name="cagridCheck" style="font-family:sans-serif;border:2px solid #d4d2d2;" required>
                          <label class="form-check-label mt-3" for="cagridCheck" style="font: normal normal normal 15px/23px Poppins;color: #000000;">
                              I agree with the <a href="" style="color:#5A71E1;text-decoration:none;font: normal normal 600 15px/23px Poppins;">Terms and conditions</a>
                          </label>
                        </div>
                      </div>
                      <input type="hidden"  id="catype" name="catype" value="Candidate"/>
                        {% for msg in messages %}
                <center>
                    <h4 style="color:red;">{{msg}}</h4>
                </center>
                {% endfor %}
                      <button type="submit" class="btn btn-primary btn-block btype" style="background-color:#486DFC;margin-top:5%;font-family:sans-serif;">SIGN UP</button>
                    </form>

models.py

class User(AbstractUser):
email = models.CharField(max_length=30,unique=True)
phone = models.CharField(max_length=30,unique=True)
terms_and_conditions_confirmed = models.BooleanField()
otp = models.CharField(max_length=6)
type = models.CharField(max_length=30)

views.py

def candidateregister(request):
  User = get_user_model()
  if request.method=='POST':
      fname = request.POST.get('cafname')
      lname = request.POST.get('calname')
      email_phone = request.POST.get('caemorpn')
      password1 = request.POST.get('capassword1')
      password2 = request.POST.get('capassword2')
      terms = request.POST.get('cagridCheck')
      type = request.POST.get('catype')
      if terms == 'on':
          terms = True
      else:
          terms = False

      regex = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b'

      if (re.fullmatch(regex, email_phone)):
          if (User.objects.filter(email=email_phone).exists()):
              messages.info(request, "Email ID Already Taken")
              return redirect('register')
          user = User.objects.create_user(first_name=fname, last_name=lname, password=password1,
                                        terms_and_conditions_confirmed=terms, type=type, email=email_phone,username=email_phone)
        user.save()
          return redirect('login')
      else:
          if (User.objects.filter(phone=email_phone).exists()):
              messages.info(request, "Phone number Already Taken")
              return redirect('register')
          user = User.objects.create_user(first_name=fname, last_name=lname, password=password1,
                                        terms_and_conditions_confirmed=terms, type=type,phone=email_phone,username=email_phone)
          user.save()
          return redirect('login')
Abin Benny
  • 125
  • 2
  • 10
  • You don't assign to User.phone in your first branch.. so perhaps it is default value (""), while it is supposed to be unique? Have you checked your database? – Jeppe Mar 28 '22 at 06:32
  • Yes. When I enter email, phone field in the database table does not contain any value. Similarly When I enter phone, email field in the database table does not contain any value. What modifications should I do in the code?@Jeppe – Abin Benny Mar 28 '22 at 06:38
  • In `candidateregister`, you have two lines that start like this: `user = User.objects.create_user(...` - in the first, you don't say `phone=email_phone` and in the second you dont say `email=email_phone`. Your model requires both of these to be unique. So maybe you need to set them as `null=True` (optional/nullable). I don't know if it can handle both `null` and `unique` - try it out. – Jeppe Mar 28 '22 at 06:42
  • First part works properly. In Second part , same error occurs. I gave `null=True` to both email and phone . That is '(1062, "Duplicate entry '' for key 'phone'")`@Jeppe – Abin Benny Mar 28 '22 at 06:53
  • Can you try explicitly setting it `phone=None` and `email=None`? This sounds like it can be set to empty string rather than null: [link](https://stackoverflow.com/questions/454436/unique-fields-that-allow-nulls-in-django) And maybe also update the records in your DB that now has empty string as values. – Jeppe Mar 28 '22 at 06:58
  • How should I explicitly set `phone=None` and `email=None`?@Jeppe – Abin Benny Mar 28 '22 at 09:32
  • `User.objects.create_user(phone=None, first_name=fname, ...` – Jeppe Mar 28 '22 at 09:38
  • I got the same error when I explicitly set `phone=None` and `email=None`. When I removed `unique=True` from email field , it works without any error. The issue is, we cannot use `unique=True` and `null=True` together. Is there any other way to implement the email field `unique=True` at the same time make it as `null'@Jeppe – Abin Benny Mar 28 '22 at 10:13

1 Answers1

0

Just set unique=False in models.py example:

class User(AbstractUser):
   email = models.CharField(max_length=30,unique=False)
   phone = models.CharField(max_length=30,unique=False)