美文网首页
2018-12-15 blog site init

2018-12-15 blog site init

作者: Jackie119 | 来源:发表于2018-12-15 16:33 被阅读0次

1. Start a site

django-admin startproject mysite
cd mysite
python manage.py migrate

migrate is to make the relevant database to store useful site information. such as administrator user.
By default use sqlite3 for database system.

2. start server

python manage.py runserver

*This is a only test mode, if you want to use django on site, need to deploy it in your server. *

python manage.py start blog

3. edit blog/models.py

from django.db import models
# Create your models here.
from django.utils import timezone
from django.contrib.auth.models import User

class Post(models.Model):
    STATUS_CHOICES = (
        ('draft','Draft'),
        ('published','Published'),
    )
    title = models.CharField(max_length=250)
    slug = models.SlugField(max_length=250,unique_for_date='publish')
    author = models.ForeignKey(User,on_delete=models.CASCADE,related_name='blog_posts')
    body = models.TextField()
    publish = models.DateTimeField(default=timezone.now)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
    status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft')

class Meta:
    ordering = ('-publish',) 

def __str__(self):
    return self.titl

in the root directory of the projeccts, run the following command:

python manage.py makemigrations blog

then django will get a file

blog/migrations/0001_initals.py

then you can print the following command to see what SQL code django will execute in the database to create table for our model.

python manage.py sqlmigrate blog 0001

the out put will be like this, depending what database system you are use:

BEGIN;
--
-- Create model Post
--
CREATE TABLE "blog_post" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "title" varchar(250) NOT NULL, "slug" varchar(250) NOT NULL, "body" text NOT NULL, "publish" datetime NOT NULL, "created" datetime NOT NULL, "updated" datetime NOT NULL, "status" varchar(10) NOT NULL, "author_id" integer NOT NULL REFERENCES "auth_user" ("id") DEFERRABLE INITIALLY DEFERRED);
CREATE INDEX "blog_post_slug_b95473f2" ON "blog_post" ("slug");
CREATE INDEX "blog_post_author_id_dd7a8485" ON "blog_post" ("author_id");
COMMIT;

the use run the following command to apply the existing migrations:

python manage.py migrate

Anytime you want to revise models.py you need to run makemigrations and migrate to to keep the database sync with it.

you should understand

I like this one.

相关文章

网友评论

      本文标题:2018-12-15 blog site init

      本文链接:https://www.haomeiwen.com/subject/upuahqtx.html