Home > Back-end >  I have used the international phone numbers(intlTelInput) in my django app but it seems the form isn
I have used the international phone numbers(intlTelInput) in my django app but it seems the form isn

Time:11-01

So i have basically used the intl-tel-input plugin in my registration form. My webapp is in django. But whenever i submit the form, i get an error which is like the phone_number field is required, even though i have filled in the number. Seems like the form isn't saving the phone number data. How can i solve this?

form temlplate looks like this:

{% load static %}
{% load crispy_forms_tags %}
<!DOCTYPE html>

<html lang="en" dir="ltr">
  <head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="/static/css/register.css">
    <link
     rel="stylesheet"
     href="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.8/css/intlTelInput.css"/>
   <script src="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.8/js/intlTelInput.min.js"></script>
 </head>
 <body>
 </body>
</html>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

 </head>
 <body>
 </body>
</html>
   </head>
<body>
  <div >
    <div >REGISTER </div>
    <div >
      <form action="#" method="post" enctype="multipart/form-data">
        {% csrf_token %}  
        <div >
          <div >
            {{form.name|as_crispy_field}}
          </div>
          <div >
            {{form.email|as_crispy_field}}
          </div>
          <div >
            <span >Phone number</span>
            <input id="phone" type="tel" name="phone" />
          </div>
          <div >
            {{form.address|as_crispy_field}}
          </div>
          <div >
            {{form.nin|as_crispy_field}}
          </div>
          <div >
            {{form.LC1_letter|as_crispy_field}}
          </div>
          <div >
            {{form.National_Id|as_crispy_field}}
          </div>
          <div >
            {{form.password1|as_crispy_field}}
          </div>
          <div >
            {{form.password2|as_crispy_field}}
          </div>
        </div>
        <div >
          <input  type="checkbox" value="" id="form2Example3c" />
          <label  for="form2Example3">
            First agree with all statements in <a href="#!">Terms of service</a> to continue
          </label>
        </div>
        <div >
          <input type="submit" value="Register" href="#">
          <input type="submit" value="Login" style="margin-left: 200px;">
        </div>
      </form>
    </div>
  </div>

</body>
<script>
  const phoneInputField = document.querySelector("#phone");
  const phoneInput = window.intlTelInput(phoneInputField, {
    onlyCountries: ['ug'],
    utilsScript:
      "https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.8/js/utils.js",
  });
  const info = document.querySelector(".alert-info");

  function process(event) {
  event.preventDefault();

  const phoneNumber = phoneInput.getNumber();

  info.style.display = "";
  info.innerHTML = `Phone number in E.164 format: <strong>${phoneNumber}</strong>`;
  }


</script>
</html>

forms.py:

from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import AbstractBaseUser
from .models import *
from django.core.exceptions import ValidationError


class RegForm(UserCreationForm):
    name = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'username'}))
    email = forms.EmailField(widget=forms.EmailInput(attrs={'placeholder': 'Enter your name', 'id':'email', 'name':'email'}))
    address = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Enter your District, Subcounty, Village' ,'id':"location"}))
    nin = forms.CharField(widget=forms.TextInput(attrs={'placeholder':'Enter your NIN', 'id':"NIN",'name':"nin"}))
    LC1_letter = forms.FileField(widget=forms.FileInput(attrs={'name':'upload'}))
    National_Id = forms.FileField(widget=forms.FileInput())

    def __init__(self, *args, **kwargs):
        super(RegForm, self).__init__(*args, **kwargs)

        for fieldname in ['LC1_letter', 'nin','password1', 'password2']:
            self.fields[fieldname].help_text = None

    class Meta:
        model = Account
        fields = ['email', 'name', 'address', 'phone_number', 'LC1_letter', 'nin', 'National_Id', 'password1', 'password2']

and views.py:

from django.shortcuts import render, redirect
from django.contrib.auth.forms import UserCreationForm
from accounts.forms import RegForm
from django.contrib.auth import login, authenticate
from .models import *
from django.contrib import messages
from django.core.files.storage import FileSystemStorage

# Create your views here.
def register(request):
    if request.method == "POST":
        form = RegForm(request.POST, request.FILES)
        if form.is_valid():
            upload = request.FILES['upload']
            fss = FileSystemStorage()
            file = fss.save(upload.name, upload)
            file_url = fss.url(file)
            form.save()
            return render(request,'main_app/base.html', {'file_url': file_url})
        else:
            print('Form is not valid')
            print(form.errors)
    else:
        form = RegForm()
    return render(request, 'accounts/register.html', {'form': form})



    

CodePudding user response:

hello please can you show the error returned? but as for now i dont see any field called phone defined in your form or an element '#phone' defined in your html

CodePudding user response:

okey i see you have specify 'phone_number' of your model to be used in your form but on the client side (html) you did not include the field in your form so went the form is submited django is trying to clean and validate the form based on fields entries then the field 'phone_number' is not found in post your data (because there is no field with the name phone_number) so that the error is returned maybe they could have returned a message like ('the field ******** is define in your form class but you did not submit it here').

To get ride of this error you can :

1- define the field on the client side like :

{{form.phone_number|as_crispy_field}}

2- or like :

<input id="id_phone_number" type="text" name="phone_number" />

as you can see in the second case the name of the field is 'phone_number' not just 'phone' as you defined it in your template .

Now depending on this you can figure out how to do you js machinery to make things work as you want it to. Happy coding

  • Related