On the last tutorial (Part 2), we have create an app, it called article. Now we will create the models to represent database model, about table and field. For your information, that "django will generate the table (with all field) and admin form from the models".

Creating models 

Now, open the models.py in article app:

There are any code on the top of the models: 

1
2
3
from django.db import models
 
# Create your models here.

and now, make the models like this:

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
from django.db import models
 
# Create your models here.
 
class Category(models.Model):
    name = models.CharField(max_length=255, null=True)
    description = models.TextField(blank=True, null=True)
    created_on = models.DateTimeField(auto_now_add=True)
    last_modified = models.DateTimeField(auto_now=True)
 
    class Meta:
        verbose_name_plural = "Category"
 
    def __unicode__(self):
        return self.name
 
class Post(models.Model):
    title = models.CharField(max_length=200, null=True)
    slug = models.SlugField(max_length=255, null=True)
    category = models.ForeignKey(Category,related_name='post_category', null=True)
    content = models.TextField(blank=True, null=True)
    created_on = models.DateTimeField(auto_now_add=True)
    last_modified = models.DateTimeField(auto_now=True)
 
    class Meta:
        verbose_name_plural = "Post"
 
    def __unicode__(self):
        return self.title

 

Have you finish type the code? Or you can copy and paste the code, but make sure about the indentation.

Activating the app

To activate the app, please add the app name to INSTALLED_APPS in setting.py

1
2
3
4
INSTALLED_APPS = (
    ...
    'article',
)

 

Now, run syncdb to create those model tables in your database: 

1
$ python manage.py syncdb

 

  generate the tables in to database

Next?

Next, we will activate the admin page, so we can create a content blog Cool 

Thanks  

Comments

Re: Django Tutorial - Create a Blog - Part 3 : Design the Models

curious | 05/02/2016, 18:31

FYI... As of Django 1.9, the syncdb command has been removed. It was deprecated in version 1.7 in favor of the migrate command.

Re: Django Tutorial - Create a Blog - Part 3 : Design the Models

Ai Jogja | 05/07/2017, 20:14

aijogja

Of course. Here, I used django version 1.6.5
Thank you

Add comment

authimage