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:
models.py: Defines a Django model
MyModel
with aPhoneNumberField
namedphone_number
.forms.py: Creates a Django form
MyModelForm
based on theMyModel
model. It includes aPhoneNumberField
for thephone_number
field.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.my_template.html: A template file containing an HTML form. It uses the
form
object generated by theMyModelForm
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.