Learn Django

Create the Model

This lesson will teach you how to create the subscriber model. The subscriber model is used to store additional information about customers who pay for the CRM Easy service. Look at the fields below to see what additional information is being stored. The model is also related to Django's User model (refer to the user_rec field).

Step 1: Create the Subscriber Model

Open /.../crmeasy/crmapp/subscribers/models.py in your IDE. Delete it's contents and type in the following.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
from django.db import models
from django.contrib.auth.models import User

class Subscriber(models.Model):
    user_rec = models.ForeignKey(User)
    address_one = models.CharField(max_length=100)
    address_two = models.CharField(max_length=100, blank=True)
    city = models.CharField(max_length=50)
    state = models.CharField(max_length=2)
    stripe_id = models.CharField(max_length=30, blank=True)

    class Meta:
        verbose_name_plural = 'subscribers'

    def __unicode__(self):
        return u"%s's Subscription Info" % self.user_rec

Code Review

Line 1: This imports Django's models class which all models will need to subclass.

Line 2: This imports the built-in User model. The Subscriber model will have a relationship to the User model, therefore we need to import it here so that it can be referenced on line 5.

Line 4: This starts the beginning of the Subscriber model. This line tells Python that this will define a class, that it will be named Subscriber, and that it should subclass models.Model.

Line 5: This is how fields/columns/attributes of the table are defined. On this line the attribute name is user_rec, and it's creating a foreign key relationship to the User model. Notice that the field is created by the model class attribute ForeignKey.

Lines 6-10: These lines define the remaining attributes of this model i.e. fields in the table. Here's a reference to all the different fields available in Django's Model utility.

Lines 12-13: This is how we give the model metadata - by defining an inner class named Meta. Here we're defining the plural name of the class. Here's a complete list of meta options.

Lines 15-16: This defines a unicode representation of objects in the model. This is particularly helpful for the Admin pages, which we'll show a little later.

Step 2: Migrate Model

Now that the model is created, we need to run two commands to have it created in the database.

Open a terminal/cmd prompt and execute the commands as you see them below:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
# Navigate to the /crmeasy/ directory
(venv)$ cd ../.../crmeasy

# Create the migration
(venv)$ python manage.py makemigrations subscribers
Migrations for 'subscribers':
  0001_initial.py:
    - Create model Subscriber

# Commit the migration
(venv)$ python manage.py migrate subscribers
Operations to perform:
  Apply all migrations: subscribers
Running migrations:
  Applying subscribers.0001_initial... OK

Step 3: Activate the Admin

Django comes with a very useful utility called the Admin Site. The Admin Site makes it easy to create, update, and delete model records. In this step you'll activate the Admin Site for the Subscriber model.

Open /.../crmeasy/crmapp/subscribers/admin.py in your IDE. Add the following code to the file.

1
2
3
4
from django.contrib import admin
from .models import Subscriber

admin.site.register(Subscriber)

Code Review

Line 1: This imports the admin utility.

Line 2: This imports the Subscriber model.

Line 4: This is the line that registers the Subscriber model with the Admin Site.

Step 4: Add the Admin URL

We'll need to add a configuration to the URL file in order to use the Admin Site. Follow these steps to do so.

Open /.../crmeasy/crmapp/urls.py in your IDE. Update it so it looks like the following.

New or modified lines are highlighted in yellow.

 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
29
30
from django.conf.urls import patterns, include, url
from django.contrib import admin

admin.autodiscover()

from marketing.views import HomePage

urlpatterns = patterns('',

    # Marketing pages
    url(r'^$', HomePage.as_view(), name="home"),

    # Subscriber related URLs
    url(r'^signup/$', 'crmapp.subscribers.views.subscriber_new', name='sub_new'),

    # Admin URL
    (r'^admin/', include(admin.site.urls)),

    # Login/Logout URLs


    # Account related URLs


    # Contact related URLS


    # Communication related URLs

)

Step 4: Create a Test Record

The next step is to add a test subscriber record to verify if the model was setup correctly. You can do so using the following steps.

First, make sure the development server is running.

1
2
3
4
5
6
7
8
# navigate to crmeasy directory (if not already there)
$ cd /<your_path_here>/crmeasy

# activate the virtual environment (if not already activated)
$ source venv/bin/activate

# start Django's development web server
(venv)$ python manage.py runserver 8000

Now you can add a record using these steps.

  1. Make sure the development server is running
  2. Open http://127.0.0.1:8000/admin
  3. Login with your admin credentials if prompted
  4. Click on the Subscribers model
  5. Click the ‘Add’ button in the upper right hand corner
  6. Fill in all the required fields and click the ‘Save’ button

Step 5: 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 the subscriber model"

Track your progress with a free account