Django官方源码解析

Django官方文档解析

标签(空格分隔): Django


创建一个应用

python manage.py startapp polls

上述操作会创建出一个polls目录,其目录结构大致如下:

polls/
    __init__.py
    admin.py
    apps.py
    migrations/
        __init__.py
    models.py
    tests.py
    views.py

创建一个视图

在polls目录中打开views.py,并输入如下代码:

from django.http import HttpResponse

def index(request):
    return HttpResponse('Hello, world. You're at the polls index.')

创建视图之后,我们需要一个将一个url地址映射到这个视图上,在polls目录里新建一个urls.py文件,并在urls.py文件中输入如下代码:

from django.urls import path
from . import views
urlpatterns = [
path('',views.index,name='index')
]

mysite/urls.py文件中的urlpatterns列表中插入一个include(),如下所示:

from django.contrib import admin
from django.urls import include, path

urlpatterns = [
    path('polls/', include('polls.urls')),
    path('admin/', admin.site.urls),
]

数据库配置

Django支持的数据库种类有:sqlite,postgresql,mysql,oracle
需要在mysite/settings.py中进行配置:

创建模型操作

在Django中写一个数据库驱动的web应用的第一步是定义模型-也就是数据库结构设计和附加的其他元数据

设计一个简单的投票应用,需要创建两个模型:问题Question和选项Choice,Question模型包括问题描述和问题发布时间,Choice模型包括选项描述和当前的得票数,多个选项对应一个问题

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)

初试API

通过如下代码进入交互式python命令行,使用Django中的各种API:

python manage.py shell

database API

>>> 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)>]>

Django管理页面

创建一个管理员账号:

python manage.py createsuperuser

输入用户名,邮件地址,和密码:

Username: admin
Email address: [email protected]
Password: **********
Password (again): *********
Superuser created successfully.

启动mysite项目:

python manage.py runserver

打开浏览器,转到你本地域名的 "/admin/" 目录, -- 比如 "http://127.0.0.1:8000/admin/" 。看见管理员登录界面:
管理员登录页面

polls/admin.py文件中,向管理页面中加入投票应用:

from django.contrib import admin

from .models import Question

admin.site.register(Question)

进行了上述操作之后,即可以通过管理页面便捷的对应用进行相应的操作:
管理页面

在templates文件夹中创建html页面

{% if latest_question_list %}
    <ul>
    {% for question in latest_question_list %}
        <li><a href="/polls/{{ question.id }}/">{{ question.question_text }}</a></li>
    {% endfor %}
    </ul>
{% else %}
    <p>No polls are available.</p>
{% endif %}

使用render函数来渲染页面:

from django.shortcuts import render

from .models import Question


def index(request):
    latest_question_list = Question.objects.order_by('-pub_date')[:5]
    context = {'latest_question_list': latest_question_list}
    return render(request, 'polls/index.html', context)

猜你喜欢

转载自www.cnblogs.com/guanzhicheng/p/9195310.html
今日推荐