Django2第一个工程

开发Django应用的典型工作流程是:先创建模型,接着最先让管理页run起来,这样你的同事或者客户就可以开始往系统里填数据。 然后,开发如何将数据展示给公众的部分。

创建一个项目:
django-admin startproject mysite

进入mysite目录,启动开发服务器:
$ python manage.py runserver
访问:http://127.0.0.1:8000
指定端口:
$ python manage.py runserver 8080

创建应用:
$ python manage.py startapp polls

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:
from django.urls import path
from . import views
urlpatterns = [
    path('', views.index, name='index'),
]

下一步是将根URLconf指向polls.urls模块。mysite/urls.py:
from django.urls import include, path
from django.contrib import admin
urlpatterns = [
    path('polls/', include('polls.urls')),
    path('admin/', admin.site.urls),
]

$ python manage.py runserver
在浏览器中转到http://localhost:8000/polls/,您应该看到文本“Hello, world. You’re at the polls index.“

mysite/settings.py配置数据库
配置时区、语言:
LANGUAGE_CODE = 'zh-Hans'
TIME_ZONE = 'Asia/Shanghai'

请注意文件顶部的INSTALLED_APPS设置。 它包含在此Django实例中激活的所有Django应用程序的名称。
其中一些应用程序至少使用了一个数据库表,所以我们需要在数据库中创建表格,然后才能使用它们。
$ python manage.py migrate

migrate命令查看INSTALLED_APPS设置,并根据mysite/settings.py文件中的数据库设置创建所有必要的数据库表,迁移命令将只对INSTALLED_APPS中的应用程序运行迁移。

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)

要将该应用程序包含在我们的项目中,我们需要在INSTALLED_APPS设置中添加对其配置类的引用。
mysite/settings.py:
INSTALLED_APPS = [
    'polls.apps.PollsConfig',
]

$ python manage.py makemigrations polls
通过运行makemigrations,您告诉Django您已经对模型进行了一些更改,并且您希望将更改存储为一个migration。

sqlmigrate命令使用迁移名称并返回它们的SQL:
$ python manage.py sqlmigrate polls 0001

再次运行migrate以在您的数据库中创建这些模型表:
$ python manage.py migrate

请记住进行模型更改的三步指南:
更改模型(在models.py中)。
运行python manage.py makemigrations为这些更改创建迁移
运行python manage.py migrate,将这些更改应用到数据库。

进入交互式Python shell并使用Django提供的API。
$ python manage.py shell
from polls.models import Question,Choice
from django.utils import timezone
Question.objects.all()
q = Question(question_text="What's new?", pub_date=timezone.now())
q.save()
q.id
Question.objects.filter(id=1)
Question.objects.filter(question_text__startswith='What')
current_year = timezone.now().year
Question.objects.get(pub_date__year=current_year)

向模型中添加__str__()方法很重要,不仅为了您在处理交互提示时的方便,还因为在Django自动生成的管理中使用了对象表示。

创建管理员账户:
$ python manage.py createsuperuser

http://127.0.0.1:8000/admin

在admin中修改polls应用程序,polls/admin.py:
from django.contrib import admin
from .models import Question
admin.site.register(Question)

创建polls/templates文件夹
mysite/settings.py中TEMPLATES:
 'APP_DIRS': True,

 创建polls/templates/polls/index.html:
 render()函数将request对象作为第一个参数,将模板名称作为第二个参数,将字典作为可选的第三个参数。返回HttpResponse对象。

 get_object_or_404()函数将Django模型作为其第一个参数和任意数量的关键字参数传递给模型管理器的get()函数。 It raises Http404 if the object doesn’t exist.
 还有一个get_list_or_404()函数,它的工作方式类似get_object_or_404()  —— 差别在于它使用filter()而不是get()。 It raises Http404 if the list is empty.

将命名空间添加到您的URLconf中.polls/urls.py:
app_name = 'polls'

polls/templates/polls/index.html:
<li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li>

you should always return an HttpResponseRedirect after successfully dealing with POST data.

默认情况下,DetailView通用视图使用名为app 名称/ model 名称_detail.html的模板。

运行测试用例polls/tests.py:
$ python manage.py test polls

What happened is this:
python manage.py test polls looked for tests in the polls application
it found a subclass of the django.test.TestCase class
it created a special database for the purpose of testing
it looked for test methods - ones whose names begin with test
in test_was_published_recently_with_future_question it created a Question instance whose pub_date field is 30 days in the future
… and using the assertIs() method, it discovered that its was_published_recently() returns True, though we wanted it to return False

Django provides a test Client to simulate a user interacting with the code at the view level.

Good rules-of-thumb include having:
a separate TestClass for each model or view
a separate test method for each set of conditions you want to test
test method names that describe their function

原文地址:https://www.cnblogs.com/liuliu3/p/10812046.html

时间: 2024-08-28 00:49:02

Django2第一个工程的相关文章

用Firefly创建第一个工程

原地址:http://blog.csdn.net/uxqclm/article/details/10382097 安装完成之后,在python script包中就存在 firefly-admin的工具. 创建第一个工程,firefly-admin.py createproject myproject,这样就创建好了myproject的工程,工程目录结构如下:startmaster.py是工程的启动模块,建立工程后可以直接启动startmaster.py进行测试.config.json是用来描述服

Ubuntu Eclipse SDL编程第一个工程

UFO SDL编程入门第一个工程 刚建立个工程,遇到了一个问题,就是SDL头文件和库路径的问题,总是提示找不到库,如图: 百度了很多种方法,都没能解决问题,很郁闷,最后在一篇安装SDL的文章中看到了,SDL里面有test程序,可以测试效果,于是乎我在test里面试了下例程,果然可以运行.既然它的可以运行,就一定有正确的路径设置.哈哈,解决问题的关键.下面请跟我一起来看看怎么解决(^水平有限啊,不足之处请多指正^) 现在这个问题解决了,希望能对大家有所帮助: 使用Eclipse编译环境,学习SDL

hibernate 的第一个工程

一.什么是Hibernate? Hibernate 是一个开放源代码的对象关系映射框架,它对JDBC进行了非常轻量级的对象封装,它将POJO与数据库表建立映射关系,是一个全自动的orm框架,hibernate可以自动生成SQL语句,自动执行,使得Java程序员可以随心所欲的使用对象编程思维来操纵数据库. Hibernate可以应用在任何使用JDBC的场合,既可以在Java的客户端程序使用,也可以在Servlet/JSP的Web应用中使用,最具革命意义的是,Hibernate可以在应用EJB的J2

Annotation 的第一个工程

一.什么是 Annotation? java.lang.annotation,接口 Annotation.对于Annotation,是Java5的新特性,JDK5引入了Metadata(元数据)很容易的就能够调用Annotations.Annotations提供一些本来不属于程序的数据,比如:一段代码的作者或者告诉编译器禁止一些特殊的错误.An annotation 对代码的执行没有什么影响.Annotations使用@annotation的形式应用于代码:类(class),属性(attribu

RTT第一个工程

第一个RTT工程 1. 配置工程 选择芯片STM32F103C8(其包含该芯片的Flash及SRAM介绍): Jlink  SW模式 output->Debug info/Browse info,可以直接定位函数和变量. 2. 修改LED相关GPIO. 3. 核对串口. RTConfig.h中定义串口终端RT_CONSOLE_DEVICE_NAME “uart1” Drivers/uarst.c中定义串口1 GPIO和baud. 4. 晶振.定义在STM32f10x_conf.h,定义外部晶振8

C语言第一个工程,简易计算器

1 # define _CRT_SECURE_NO_WARNINGS 2 #include <stdio.h> 3 int main() 4 { 5 6 7 while (true) 8 { 9 10 double a, b; 11 12 char or; 13 printf("请输入第一个数字:"); 14 scanf("%lf", &a); 15 printf("请输入运算符:"); 16 scanf("%s&q

TeamCity : 配置第一个工程

前面我们已经创建了TeamCity Server 和一个 Agent,接下来我们为一个.net core 控制台程序配置自动化的编译. 创建 .net core 项目 我们在本地创建一个简单的 .net core demo程序 hello (这里假设您已经安装了.net core 的 SDK): mkdir hello cd hello dotnet new dotnet restore dotnet run 如果能看到输出 "Hello World!",就说明demo 程序已经OK了

NORDIC nRF24LE1 学习笔记 Day01 安装环境与创建第一个工程

首先 First 准备软件安装包 perpare the softwaer installation pachage ①Keil C51(Version 9.00 or  newer) ②nRFgo Studio(Version 1.4 or newer) ③nRFgo SDK(Version 2.2 or newer) ④nRFprobe (Version 1.2.0.5585 or newer) 准备硬件 perpare the Hardware ①nRFgo Starter Kit(nRF

qt 创建第一个工程

首先新建一个项目 创建文件名 创建工程名 原文地址:https://www.cnblogs.com/fanhua666/p/12289370.html