PhoneNumberField django forms

# models.py
from django.db import models
from phonenumber_field.modelfields import PhoneNumberField

class MyModel(models.Model):
    phone_number = PhoneNumberField()

# forms.py
from django import forms
from .models import MyModel

class MyModelForm(forms.ModelForm):
    class Meta:
        model = MyModel
        fields = ['phone_number']

# views.py
from django.shortcuts import render
from .forms import MyModelForm

def my_view(request):
    if request.method == 'POST':
        form = MyModelForm(request.POST)
        if form.is_valid():
            # Do something with the valid form data
            form.save()
    else:
        form = MyModelForm()
    return render(request, 'my_template.html', {'form': form})

# my_template.html
<form method="post" action="{% url 'my_view' %}">
  {% csrf_token %}
  {{ form.as_p }}
  <button type="submit">Submit</button>
</form>

Explanation:

  1. models.py: Defines a Django model MyModel with a PhoneNumberField named phone_number.

  2. forms.py: Creates a Django form MyModelForm based on the MyModel model. It includes a PhoneNumberField for the phone_number field.

  3. views.py: Defines a view function my_view that handles both GET and POST requests. On a POST request, it validates the form, saves the data if valid, and renders the template. On a GET request, it creates a new form instance for rendering.

  4. my_template.html: A template file containing an HTML form. It uses the form object generated by the MyModelForm class. The form includes a CSRF token and a submit button.

Note: Make sure to replace 'my_view' with the actual name of your view in the action attribute of the form.