创建project named mysite
django-admin startproject mysite
命令行进入项目目录
运行服务器
python manage.py runserver
创建APP named polls
python manage.py startapp polls
Let’s write the first view. Open the file polls/views.py
and put the following Python code in it:
polls/views.py
from django.http import HttpResponse
def index(request):
return HttpResponse("Hello, world. You're at the polls index.")
create a file called urls.py in polls
polls/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
]
在project里指向APP polls
In mysite/urls.py
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('polls/', include('polls.urls')),
path('admin/', admin.site.urls),
]
editing mysite/settings.py
TIME_ZONE = 'Asia/Shanghai'
Some of INSTALLED_APPS make use of at least one database table, though, so we need to create the tables in the database before we can use them. To do that, run the following command:
python manage.py migrate
The migrate
command looks at the INSTALLED_APPS
setting and creates any necessary database tables according to the database settings in your mysite/settings.py
file and the database migrations shipped with the app
migrations are entirely derived from your models file, and are essentially just a history that Django can roll through to update your database schema to match your current models.
Edit the polls/models.py
from django.db import models
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
To include the app in our project, we need to add a reference to its configuration class in the INSTALLED_APPS
setting. The PollsConfig
class is in the polls/apps.py
file, so its dotted path is 'polls.apps.PollsConfig'
. Edit the mysite/settings.py
file and add that dotted path to the INSTALLED_APPS
setting. It’ll look like this:
mysite/settings.py
INSTALLED_APPS = [
'polls.apps.PollsConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
Migrations are how Django stores changes to your models (and thus your database schema) - they’re just files on disk
Migrations are very powerful and let you change your models over time, as you develop your project, without the need to delete your database or tables and make new ones - it specializes in upgrading your database live, without losing data.
remember the three-step guide to making model changes:
- Change your models (in
models.py
). - Run
python manage.py makemigrations
to create migrations for those changes - Run
python manage.py migrate
to apply those changes to the database.
合并python manage.py makemigrations&python manage.py migrate
The reason that there are separate commands to make and apply migrations is because you’ll commit migrations to your version control system and ship them with your app; they not only make your development easier, they’re also usable by other developers and in production.只要向服务器commit migrations,然后python manage.py migrate就可以
upgrading your database live
命令行操作数据库
$ python manage.py shell
>>> from polls.models import Choice, Question # Import the model classes we just wrote.
# No questions are in the system yet.
>>> Question.objects.all()
<QuerySet []>
# Create a new Question.
# Support for time zones is enabled in the default settings file, so
# Django expects a datetime with tzinfo for pub_date. Use timezone.now()
# instead of datetime.datetime.now() and it will do the right thing.
>>> from django.utils import timezone
>>> q = Question(question_text="What's new?", pub_date=timezone.now())
# Save the object into the database. You have to call save() explicitly.
>>> q.save()
# Now it has an ID.
>>> q.id
1
# Access model field values via Python attributes.
>>> q.question_text
"What's new?"
>>> q.pub_date
datetime.datetime(2012, 2, 26, 13, 0, 0, 775217, tzinfo=<UTC>)
# Change values by changing the attributes, then calling save().
>>> q.question_text = "What's up?"
>>> q.save()
# objects.all() displays all the questions in the database.
>>> Question.objects.all()
<QuerySet [<Question: Question object (1)>]>
Creating an admin user
python manage.py createsuperuser
python manage.py runserver
http://127.0.0.1:8000/admin/
we need to tell the admin that Question
objects have an admin interface. To do this, open the polls/admin.py
file, and edit it to look like this:
polls/admin.py
from django.contrib import admin from .models import Question admin.site.register(Question)