Learn Django

New Contact - Create Form

The first resource to create is the form that will be used to create new contacts, and eventually edit existing ones. To make setup as easy as possible, it will be created as a ModelForm.

Step 1: Create the Forms File

Follow these steps to create the forms file.

  1. Navigate to /.../crmeasy/crmapp/contacts
  2. Create a file there named forms.py
  3. Open this file in your IDE

Step 2: Create the ContactForm Class

Type in the following code into forms.py.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
from django import forms

from .models import Contact


class ContactForm(forms.ModelForm):
    class Meta:
        model = Contact
        fields = ('first_name', 'last_name',
                  'role', 'phone', 'email', 'account',
        )
        widgets = {
            'first_name': forms.TextInput(
                attrs={'placeholder':'First Name', 'class':'form-control'}
            ),
            'last_name': forms.TextInput(
                attrs={'placeholder':'Last Name', 'class':'form-control'}
            ),
            'role': forms.TextInput(
                attrs={'placeholder':'Role', 'class':'form-control'}
            ),
            'phone': forms.TextInput(
                attrs={'placeholder':'Phone', 'class':'form-control'}
            ),
            'email': forms.TextInput(
                attrs={'placeholder':'Email', 'class':'form-control'}
            ),
        }

Step 3: Commit Changes

Execute these commands to commit your changes in Git.

1
2
3
4
5
# add files
(venv)$ git add .

# commit files
(venv)$ git commit -m "created new contact form"

Track your progress with a free account