【2】依照Django官网,创建一个web 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-16 00:20:29

【2】依照Django官网,创建一个web app的相关文章

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

【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 cl

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

今天继续学习外键的使用. 当我们有了category.series和很多tutorials时,我们查看某个tutorial,可能需要这样的路径http://127.0.0.1:8000/category/series/tutorial,这样看上去十分的繁琐,我们希望无论是在category下还是在series.tutorials下,都只有一级路径. 那么如何做呢?首先在views.py中,我们定义一个single_slug函数: def single_slug(request, single_s

【3】依照django官网:创建一个web app

1 Creating an admin user $ python manage.py createsuperuser UserName: wuwh Password:   ganbare 2  Start the development server? $ python manage.py runserver 8088 visit :http://127.0.0.1:8000/admin/ 3 .Make the poll app modifiable in the admin from dj

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

前面我们已经建立了模型Tutorial,也已经可以用Navicat Premium打开数据看查看数据,接下来我们通过建立admin账户来上传数据. 在命令行执行如下命令来创建用户: python manage.py createsuperuser 然后输入相应的用户名.邮箱和密码,邮箱可随意填写,接下来执行 python manage.py runserver ,在浏览器输入 http://127.0.0.1:8000/admin/看到下图,输入刚才创建的用户名和密码: 我们可以在User中看到

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

今天开始学习网页风格和设计,就像python有Web框架一样,也有一些CSS框架.对于CSS框架,我们可以使用默认的样式,也可以在原基础上编辑修改.本教程使用的是materialize这个CSS框架[1],首页界面如下: 点解GET STARTED,我们可以把它下载到本地使用,也可以直接复制相应的链接使用. 为了套用如下这个Cards界面,我们直接将代码复制到home.html: 修改后的home.html内容如下: {% load static %} <!-- Compiled and min

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

今天来实现网站的登入和登出功能. 首先我们需要在urls.py中添加路径,注意此处的路径和在导航栏中设置的文字路径保持一致: from django.urls import path from . import views app_name = 'main' #此处为了urls的命名空间 urlpatterns = [ path('', views.homepage, name='homepage'), path('register/', views.register, name='regist

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 ,并点