【2】按照Django官网,创建一个web app 创建app/创建相应的数据库表

1. Creating app

$ python manage.py startapp polls

That’ll create a directory polls,
which is laid out like this:

polls/
    __init__.py
    admin.py
    migrations/
        __init__.py
    models.py
    tests.py
    views.py
1.1 Edit 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‘)
  def __str__(self):              # __unicode__ on Python 2
      return self.question_text
  def was_published_recently(self):
      return self.pub_date >= timezone.now()

class Choice(models.Model): question = models.ForeignKey(Question) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0)

    def __str__(self):              # __unicode__ on Python 2
     return self.choice_text
1.2 Edit the mysite/settings.py file again, and change the INSTALLED_APPS setting to include the string ‘polls‘:

INSTALLED_APPS = (
    ‘django.contrib.admin‘,
    ‘django.contrib.auth‘,
    ‘django.contrib.contenttypes‘,
    ‘django.contrib.sessions‘,
    ‘django.contrib.messages‘,
    ‘django.contrib.staticfiles‘,
    ‘polls‘,
)
1.3 Now Django knows to include the polls app. Let’s run another command:

$ python manage.py makemigrations polls
1.4    Now, run migrate again to create those model tables in your database:
       1.4.1   python manage.py check;
      1.4.2  python manage.pymigrate
1.5    

Playing with the API

1.5.1 python manage.py shell   1.5.2
>>> from polls.models import Question, Choice   # Import the model classes we just wrote.

# No questions are in the system yet.
>>> Question.objects.all()
[]

# 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. Note that this might say "1L" instead of "1", depending
# on which database you‘re using. That‘s no biggie; it just means your
# database backend prefers to return integers as Python long integer
# objects.
>>> 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()
[<Question: Question object>]


>>> from polls.models import Question, Choice

# Make sure our __str__() addition worked.
>>> Question.objects.all()
[<Question: What‘s up?>]

# Django provides a rich database lookup API that‘s entirely driven by
# keyword arguments.
>>> Question.objects.filter(id=1)
[<Question: What‘s up?>]
>>> Question.objects.filter(question_text__startswith=‘What‘)
[<Question: What‘s up?

>]

# Get the question that was published this year.
>>> from django.utils import timezone
>>> current_year = timezone.now().year
>>> Question.objects.get(pub_date__year=current_year)
<Question: What‘s up?>

# Request an ID that doesn‘t exist, this will raise an exception.
>>> Question.objects.get(id=2)
Traceback (most recent call last):
    ...
DoesNotExist: Question matching query does not exist.

# Lookup by a primary key is the most common case, so Django provides a
# shortcut for primary-key exact lookups.
# The following is identical to Question.objects.get(id=1).
>>> Question.objects.get(pk=1)
<Question: What‘s up?

>

# Make sure our custom method worked.
>>> q = Question.objects.get(pk=1)
>>> q.was_published_recently()
True

# Give the Question a couple of Choices. The create call constructs a new
# Choice object, does the INSERT statement, adds the choice to the set
# of available choices and returns the new Choice object. Django creates
# a set to hold the "other side" of a ForeignKey relation
# (e.g. a question‘s choice) which can be accessed via the API.
>>> q = Question.objects.get(pk=1)

# Display any choices from the related object set -- none so far.
>>> q.choice_set.all()
[]

# Create three choices.
>>> q.choice_set.create(choice_text=‘Not much‘, votes=0)
<Choice: Not much>
>>> q.choice_set.create(choice_text=‘The sky‘, votes=0)
<Choice: The sky>
>>> c = q.choice_set.create(choice_text=‘Just hacking again‘, votes=0)

# Choice objects have API access to their related Question objects.
>>> c.question
<Question: What‘s up?

>

# And vice versa: Question objects get access to Choice objects.
>>> q.choice_set.all()
[<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]
>>> q.choice_set.count()
3

# The API automatically follows relationships as far as you need.
# Use double underscores to separate relationships.
# This works as many levels deep as you want; there‘s no limit.
# Find all Choices for any question whose pub_date is in this year
# (reusing the ‘current_year‘ variable we created above).
>>> Choice.objects.filter(question__pub_date__year=current_year)
[<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]

# Let‘s delete one of the choices. Use delete() for that.
>>> c = q.choice_set.filter(choice_text__startswith=‘Just hacking‘)
>>> c.delete()

时间: 2024-10-03 07:41:01

【2】按照Django官网,创建一个web app 创建app/创建相应的数据库表的相关文章

eclipes创建一个web项目web.xml不能自动更新的原因(web.xml和@WebServlet的作用)

在eclipse中创建一个Web项目的时候,虽然有web.xml生成,但是再添加Servlet类文件的时候总是看不见web.xml的更新,所以异常的郁闷!上网查了查,原来我们在创建Web项目的时候,会弹出一个对话框,“Dynamic web module version”这个选项默认成了3.0,按照老规范,应该是在eclipse的WebContent \ WEB-INF \ 目录下创建web.xml的.而新规范是可以不用web.xml的,如tomcat 7.0就支持新规范,这样相关的servle

使用eclipse插件创建一个web project

使用eclipse插件创建一个web project 首先创建一个Maven的Project如下图 我们勾选上Create a simple project (不使用骨架) 这里的Packing 选择 war的形式 由于packing是war包,那么下面也就多出了webapp的目录 由于我们的项目要使用eclipse发布到tomcat下面,这里我们需要先把项目转成dynamic web project 在我们的项目上点击右键,选择properties 并找到 Project Facets ,并点

使用CXF+spring+restful创建一个web的接口项目

此文为http://blog.csdn.net/zxnlmj/article/details/28880303的下文,在其基础上添加restful功能 1.添加restful的所需jar包 jsr311-api-1.0.jar CXF与JAX-RS版本对应问题,参考自:http://bioubiou.iteye.com/blog/1866871 CXF支持REST风格的Web服务:JAX-RS2.0(JSR-339)和JAX-RS1.1(JSR-311)的Java API. CXF2.7.0支持

使用CXF+spring创建一个web的接口项目

一.web project整合spring 1.1.打开Myeclipse,建立web project(eclipse为dynamic web project),使用J2EE5.0. 1.2.添加Srping的基本jar包(无需事务等) org.springframework.beans-3.1.1.RELEASE.jar commons-logging.jar org.springframework.aop-3.1.1.RELEASE.jar org.springframework.asm-3

IntelliJ IDEA 中配置Maven以及创建一个Web项目

IntelliJ IDEA 中配置Maven Step.1 File-Settings Step.2 使用Maven创建一个Web项目 Step.1 File-New-Project Step.2

自己动手创建一个Web Server(非Socket实现)

目录 介绍 Web Server在Web架构系统中的作用 Web Server与Web网站程序的交互 HTTPListener与Socket两种方式的差异 附带Demo源码概述 Demo效果截图 总结 介绍 本篇文章主要介绍使用HTTPListener类型自己动手创建一个Web Server,创建的Web Server能够接收来自浏览器端的HTTP请求,并且能够传递给对应的Web站点进行处理,最后将处理结果(Html或者其他格式)返回给浏览器. 博主前面曾经介绍过使用Socket模拟Web Se

flask 创建一个web

创建一个web pip install flask from flask import Flask app=Flask(__name__) @app.route('/') def index(): return 'hello' 运行 flask run 原文地址:https://www.cnblogs.com/buchizaodian/p/11142154.html

Bootstrap--模仿官网写一个页面

本文参考Bootstrap官方文档写了简单页面来熟悉Bootstrap的栅格系统.常用CSS样.Javascript插件和部分组件. 以下html代码可以直接复制本地运行: BootstrapPage1:常见的一种页面类型,页面导航,左侧分类.右侧新闻列表: <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8&q

Anaconda+django写出第一个web app(一)

在安装好Anaconda和django之后,我们就可以开始创建自己的第一个Web app,那么首先创建一个空文件夹,之后创建的文件都在这个文件夹内. 启动命令行进入此文件夹内,可以先通过如下命令查看一下自己的python版本和django版本. python --version  django-admin --version 我的python和django版本分别是3.7.0和2.1.5 使用如下命令创建第一个项目,命名为mysite. django-admin startproject mys

JavaWeb学习(三) : 如何在 Eclipse 中创建一个Web 项目并成功运行?

前置条件 : 1.确保已安装 Eclipse.Tomcat 服务器安装包 2.jdk.环境变量都已配置成功. 3.注意在安装 Eclipse 时一定要选择第二个有 Web 项目的进行安装, 不然安装成功后还需要下载很多的插件,增加了不必要的麻烦. 创建步骤 : 1.将本地 Tomcat 服务器添加 进去: 首先打开 Window -- preference 搜索 server 双击 Runtime Environments 点击 Add,找到对应的你下载的 TomCat 服务器,进行添加,我的