Skip to content
Advertisement

Django form: phone field not showing

I would like to create a contact form on my Django website. For now, this is my code:

models.py:

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

class Client(models.Model):
    phone = PhoneNumberField(null=False, blank=True, unique=True)

forms.py:

from django import forms
from phonenumber_field.modelfields import PhoneNumberField

class ContactForm(forms.Form):
    fullName = forms.CharField(max_length=100)
    email = forms.EmailField()
    phone = PhoneNumberField()
    message = forms.CharField(widget=forms.Textarea)

views.py:

def contact(request):
    # return render(request, 'contact.html')
    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():
            # send email code goes here
            return HttpResponse('Thanks for contacting us!')
    else:
        form = ContactForm()

    return render(request, 'contact.html', {'form': form})

html:

<form method="post">
    {%% csrf_token %%}
    {{ form.as_p }}
    <input type="submit" value="Submit" />
</form>

I of course installed phonenumber_field and added it in settings.py

This is the result, phone field missing: form

Any help is hugely appreciated! Thanks for your time.

Advertisement

Answer

You used a model field, whereas for a form, you need a form field:

from django import forms
#            a <b>form</b> field &downarrow;
from phonenumber_field.<b>formfields</b> import PhoneNumberField

class ContactForm(forms.Form):
    fullName = forms.CharField(max_length=100)
    email = forms.EmailField()
    phone = PhoneNumberField()
    message = forms.CharField(widget=forms.Textarea)
Advertisement