Django builds a blog quickly and Django builds a blog
If preparation:
1. Python
2. Django
3. Git
Install Python:
Download from official website
Install Django:
# Install Django $ pip install django in the latest version # or specify the installation version pip install-v django = 1.7.1
Now, createmy_blog
Django project:
$ django-admin.py startproject my_blog
Create a Django app (article ):
$ python manage.py startapp article
So far, the project structure is as follows:
── article│ ├── __init__.py│ ├── admin.py│ ├── migrations│ │ └── __init__.py│ ├── models.py│ ├── tests.py│ └── views.py├── db.sqlite3├── manage.py├── my_blog ├── __init__.py ├── __pycache__ │ ├── __init__.cpython-34.pyc │ ├── settings.cpython-34.pyc │ ├── urls.cpython-34.pyc │ └── wsgi.cpython-34.pyc ├── settings.py ├── urls.py └── wsgi.py
Add the new app under my_blog/setting. py:
INSTALLED_APPS = (... 'Article', # enter the app name here)
Run the program!Start the development server in Django:
$ python manage.py runserver
If the preceding interface is displayed, the operation is successful.
Command Summary
Python manage. py <command> [options] # Django Command python manange. py-h help document django-admin.py startproject my_blog # Create Project python manage. py startapp article # create app
Django Model:
- Every
Django Model
Are inherited fromdjango.db.models.Model
- In
Model
Each of these attributesattribute
All represent a database field
- Pass
Django Model API
You can add, delete, modify, and query a database without writing some database query statements.
Set database:
After the Django project is built, the SQLite database is set by default. You can view and modify the database settings in my_blog/setting. py.
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), }}
You can also set other databases, suchMySQL, PostgreSQL
To make it simple, use the default database settings.
Create models:
Write the following code in my_blog/article/models. py:
From django. db import models # Create your models here. class Article (models. model): title = models. charField (max_length = 100) # blog topic category = models. charField (max_length = 50, blank = True) # blog tag date_time = models. dateTimeField (auto_now_add = True) # blog date content = models. textField (blank = True, null = True) # blog post body # python2 use _ unicode __, python3 use _ str _ def _ str _ (self ): return self. title class Meta: # sort by time drop ordering = ['-date_time']
Where__str__(self)
How does the function Article object express itself?<Article: Article object>
This function tells the system to use the title field to represent the object.
CharField
Used to store strings. max_length sets the maximum length.
TextField
Used to store large volumes of text
DateTimeField
Used for storage time. auto_now_add sets True to automatically set the object increase time.