首页>>后端>>Python->django怎么设置usetz

django怎么设置usetz

时间:2023-12-02 本站 点击:0

导读:很多朋友问到关于django怎么设置usetz的相关问题,本文首席CTO笔记就来为大家做个详细解答,供大家参考,希望对大家有所帮助!一起来看看吧!

本文目录一览:

1、django视图中怎么把从前端获取的user作为全局变量2、求教Django中model类型为DateTimeField在查询时的问题3、如何创建一个Django网站4、如何在django上自动创建createuperuser

django视图中怎么把从前端获取的user作为全局变量

有时候,我们需要Templates模板页面可以使用一些变量。这些变量我们在views.py响应时没有返回设置的变量。例如,如下代码:

#coding:utf-8

from django.shortcuts import render

def index(request):

context = {}

context['title'] = '测试标题'

return render(request, 'index.html', context)

上面是某个views.py的方法之一。它将渲染index.html模版(Template)页面,并返回context字典。该字典是传入变量信息给前端页面。对应的index.html如下:

 

html

head/head

body

h3{{title}}/h3

p是否登录:{{request.user.is_authenticated}}/p

/body

/html

响应结果除了有title变量值之外,还有是否登录信息。该登录信息来自request变量,问题是上面views.py中返回结果的context中没有写入request变量。而模版也没却有可以获取该变量。

这个当时不是无中生有,我一步一步剖析给大家看。原理讲明白之后,就自然懂得如何设置模版(Templates)的全局变量或者叫默认变量。

render方法是render_to_response方法的简写方式。上面的views.py代码相当于如下:

 

#coding:utf-8

from django.shortcuts import render_to_response

from django.template import RequestContext

def index(request):

context = {}

context['title'] = '测试标题'

return render_to_response('index.html', context, RequestContext(request))

如果去掉render_to_response的第三个参数,即RequestContext(request)部分。

渲染index.html模版页面就无法得到{{request.user.is_authenticated}}的值,即没有传递request变量给前端页面。很明显RequestContext很关键。

有关RequestContext的内容可以从Django官方文档查得。

该类实例化时会解析settings中的Templates设置中的context_processors配置。新建Django项目settings.py文件中默认的Templates设置如下:

 

TEMPLATES = [

{

'BACKEND': 'django.template.backends.django.DjangoTemplates',

'DIRS': [],

'APP_DIRS': True,

'OPTIONS': {

'context_processors': [

'django.template.context_processors.debug',

'django.template.context_processors.request',

'django.contrib.auth.context_processors.auth',

'django.contrib.messages.context_processors.messages',

],

},

},

]

大家可发现context_processors有一系列设置,其中根据django.template.context_processors.request的路径找到Django的相关源码。

Django安装在Python的安装目录下Lib/site-packages/目录中,找到django/template/context_processors.py文件,打开可看到request方法:

 

def request(request):

return {'request': request}

该方法返回一个字典,key为request,value为request对象。很明显,render中的request对象就是通过加载settings中的context_processors列表方法得到字典项。

我们也可以采用这种方法,给Django项目设置全局的模版变量。例如,我的Django名称为myproject,在myproject/myproject目录中创建一个contexts.py文件,代码如下:

 

#coding:utf-8

from django.conf import settings

# 得到语言设置

def lang(request):

return {'lang': settings.LANGUAGE_CODE}

该文件的方法需要request参数,最后需要返回一个字典即可。

再打开settings.py文件,在Templates中添加刚才写的方法引用:

 

TEMPLATES = [

{

'BACKEND': 'django.template.backends.django.DjangoTemplates',

'DIRS': [],

'APP_DIRS': True,

'OPTIONS': {

'context_processors': [

'django.template.context_processors.debug',

'django.template.context_processors.request',

'django.contrib.auth.context_processors.auth',

'django.contrib.messages.context_processors.messages',

# 自定义模版全局变量(默认变量)

'myproject.contexts.lang',

],

},

},

]

添加模版全局变量之后,我们可以在任意位置渲染模版页面无需再手动写相关代码即可使用该变量。

求教Django中model类型为DateTimeField在查询时的问题

Django还有一些warning打印出来:/Users/jay/workspace/te/env/lib/python2.7/site-packages/django/db/models/fields/__init__.py:903: RuntimeWarning: DateTimeField TestSuite.update_time received a naive datetime (2014-06-15 14:38:37.873873) while time zone support is active. RuntimeWarning)

这个warning的原因是,Django配置为使用timezone的datetime格式,而datetime.now是不包含timezone信息的。

如果不需要在程序中特别处理时区(timezone-aware),在Django项目的settings.py文件中,可以直接设置为“USE_TZ = False”就省心了。然后,在models.py中简单的设置为“ create_time = models.DateTimeField(auto_now_add=True)”和“update_time = models.DateTimeField(auto_now=True)”。

如果还要保持USE_TZ=True,则可设置为“default=datetime.now().replace(tzinfo=utc)” 。

如何创建一个Django网站

1. 创建项目

运行下面命令就可以创建一个 django 项目,项目名称叫 mysite :

$ django-admin.py startproject mysite

创建后的项目目录如下:

mysite

├── manage.py

└── mysite

├── __init__.py

├── settings.py

├── urls.py

└── wsgi.py

1 directory, 5 files

说明:

__init__.py :让 Python 把该目录当成一个开发包 (即一组模块)所需的文件。 这是一个空文件,一般你不需要修改它。

manage.py :一种命令行工具,允许你以多种方式与该 Django 项目进行交互。 键入python manage.py help,看一下它能做什么。 你应当不需要编辑这个文件;在这个目录下生成它纯是为了方便。

settings.py :该 Django 项目的设置或配置。

urls.py:Django项目的URL路由设置。目前,它是空的。

wsgi.py:WSGI web 应用服务器的配置文件。更多细节,查看 How to deploy with WSGI

接下来,你可以修改 settings.py 文件,例如:修改 LANGUAGE_CODE、设置时区 TIME_ZONE

SITE_ID = 1

LANGUAGE_CODE = 'zh_CN'

TIME_ZONE = 'Asia/Shanghai'

USE_TZ = True

上面开启了 [Time zone]() 特性,需要安装 pytz:

$ sudo pip install pytz

2. 运行项目

在运行项目之前,我们需要创建数据库和表结构,这里我使用的默认数据库:

$ python manage.py migrate

Operations to perform:

Apply all migrations: admin, contenttypes, auth, sessions

Running migrations:

Applying contenttypes.0001_initial... OK

Applying auth.0001_initial... OK

Applying admin.0001_initial... OK

Applying sessions.0001_initial... OK

然后启动服务:

$ python manage.py runserver

你会看到下面的输出:

Performing system checks...

System check identified no issues (0 silenced).

January 28, 2015 - 02:08:33

Django version 1.7.1, using settings 'mysite.settings'

Starting development server at

Quit the server with CONTROL-C.

这将会在端口8000启动一个本地服务器, 并且只能从你的这台电脑连接和访问。 既然服务器已经运行起来了,现在用网页浏览器访问 。你应该可以看到一个令人赏心悦目的淡蓝色 Django 欢迎页面它开始工作了。

你也可以指定启动端口:

$ python manage.py runserver 8080

以及指定 ip:

$ python manage.py runserver 0.0.0.0:8000

3. 创建 app

前面创建了一个项目并且成功运行,现在来创建一个 app,一个 app 相当于项目的一个子模块。

在项目目录下创建一个 app:

$ python manage.py startapp polls

如果操作成功,你会在 mysite 文件夹下看到已经多了一个叫 polls 的文件夹,目录结构如下:

polls

├── __init__.py

├── admin.py

├── migrations

│ └── __init__.py

├── models.py

├── tests.py

└── views.py

1 directory, 6 files

4. 创建模型

每一个 Django Model 都继承自 django.db.models.Model

在 Model 当中每一个属性 attribute 都代表一个 database field

通过 Django Model API 可以执行数据库的增删改查, 而不需要写一些数据库的查询语句

打开 polls 文件夹下的 models.py 文件。创建两个模型:

import datetime

from django.db import models

from django.utils import timezone

class Question(models.Model):

question_text = models.CharField(max_length=200)

pub_date = models.DateTimeField('date published')

def was_published_recently(self):

return self.pub_date = timezone.now() - datetime.timedelta(days=1)

class Choice(models.Model):

question = models.ForeignKey(Question)

choice_text = models.CharField(max_length=200)

votes = models.IntegerField(default=0)

然后在 mysite/settings.py 中修改 INSTALLED_APPS 添加 polls:

INSTALLED_APPS = (

'django.contrib.admin',

'django.contrib.auth',

'django.contrib.contenttypes',

'django.contrib.sessions',

'django.contrib.messages',

'django.contrib.staticfiles',

'polls',

)

在添加了新的 app 之后,我们需要运行下面命令告诉 Django 你的模型做了改变,需要迁移数据库:

$ python manage.py makemigrations polls

你会看到下面的输出日志:

Migrations for 'polls':

0001_initial.py:

- Create model Choice

- Create model Question

- Add field question to choice

你可以从 polls/migrations/0001_initial.py 查看迁移语句。

运行下面语句,你可以查看迁移的 sql 语句:

$ python manage.py sqlmigrate polls 0001

输出结果:

BEGIN;

CREATE TABLE "polls_choice" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "choice_text" varchar(200) NOT NULL, "votes" integer NOT NULL);

CREATE TABLE "polls_question" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "question_text" varchar(200) NOT NULL, "pub_date" datetime NOT NULL);

CREATE TABLE "polls_choice__new" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "choice_text" varchar(200) NOT NULL, "votes" integer NOT NULL, "question_id" integer NOT NULL REFERENCES "polls_question" ("id"));

INSERT INTO "polls_choice__new" ("choice_text", "votes", "id") SELECT "choice_text", "votes", "id" FROM "polls_choice";

DROP TABLE "polls_choice";

ALTER TABLE "polls_choice__new" RENAME TO "polls_choice";

CREATE INDEX polls_choice_7aa0f6ee ON "polls_choice" ("question_id");

COMMIT;

你可以运行下面命令,来检查数据库是否有问题:

$ python manage.py check

再次运行下面的命令,来创建新添加的模型:

$ python manage.py migrate

Operations to perform:

Apply all migrations: admin, contenttypes, polls, auth, sessions

Running migrations:

Applying polls.0001_initial... OK

总结一下,当修改一个模型时,需要做以下几个步骤:

修改 models.py 文件

运行 python manage.py makemigrations 创建迁移语句

运行 python manage.py migrate,将模型的改变迁移到数据库中

你可以阅读 django-admin.py documentation,查看更多 manage.py 的用法。

创建了模型之后,我们可以通过 Django 提供的 API 来做测试。运行下面命令可以进入到 python shell 的交互模式:

$ python manage.py shell

下面是一些测试:

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]

打印所有的 Question 时,输出的结果是 [Question: Question object],我们可以修改模型类,使其输出更为易懂的描述。修改模型类:

from django.db import models

class Question(models.Model):

# ...

def __str__(self): # __unicode__ on Python 2

return self.question_text

class Choice(models.Model):

# ...

def __str__(self): # __unicode__ on Python 2

return self.choice_text

接下来继续测试:

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)

# 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()

上面这部分测试,涉及到 django orm 相关的知识,详细说明可以参考 Django中的ORM。

5. 管理 admin

Django有一个优秀的特性, 内置了Django admin后台管理界面, 方便管理者进行添加和删除网站的内容.

新建的项目系统已经为我们设置好了后台管理功能,见 mysite/settings.py:

INSTALLED_APPS = (

'django.contrib.admin', #默认添加后台管理功能

'django.contrib.auth',

'django.contrib.contenttypes',

'django.contrib.sessions',

'django.contrib.messages',

'django.contrib.staticfiles',

'mysite',

)

同时也已经添加了进入后台管理的 url, 可以在 mysite/urls.py 中查看:

url(r'^admin/', include(admin.site.urls)), #可以使用设置好的url进入网站后台

接下来我们需要创建一个管理用户来登录 admin 后台管理界面:

$ python manage.py createsuperuser

Username (leave blank to use 'june'): admin

Email address:

Password:

Password (again):

Superuser created successfully.

总结

最后,来看项目目录结构:

mysite

├── db.sqlite3

├── manage.py

├── mysite

│ ├── __init__.py

│ ├── settings.py

│ ├── urls.py

│ ├── wsgi.py

├── polls

│ ├── __init__.py

│ ├── admin.py

│ ├── migrations

│ │ ├── 0001_initial.py

│ │ ├── __init__.py

│ ├── models.py

│ ├── templates

│ │ └── polls

│ │ ├── detail.html

│ │ ├── index.html

│ │ └── results.html

│ ├── tests.py

│ ├── urls.py

│ ├── views.py

└── templates

└── admin

└── base_site.htm

通过上面的介绍,对 django 的安装、运行以及如何创建视 图和模型有了一个清晰的认识,接下来就可以深入的学习 django 的自动化测试、持久化、中间件、国 际 化等知识。

如何在django上自动创建createuperuser

1. 创建项目

运行面命令创建 django 项目项目名称叫 mysite :

$ django-admin.py startproject mysite

创建项目目录:

mysite

├── manage.py

└── mysite

├── __init__.py

├── settings.py

├── urls.py

└── wsgi.py

1 directory, 5 files

说明:

__init__.py :让 Python 该目录发包 (即组模块)所需文件 空文件般需要修改

manage.py :种命令行工具允许种式与该 Django 项目进行交互 键入python manage.py help看能做 应需要编辑文件;目录纯便

settings.py :该 Django 项目设置或配置

urls.py:Django项目URL路由设置目前空

wsgi.py:WSGI web 应用服务器配置文件更细节查看 How to deploy with WSGI

接修改 settings.py 文件例:修改 LANGUAGE_CODE、设置区 TIME_ZONE

SITE_ID = 1

LANGUAGE_CODE = 'zh_CN'

TIME_ZONE = 'Asia/Shanghai'

USE_TZ = True

面启 [Time zone]() 特性需要安装 pytz:

$ sudo pip install pytz

2. 运行项目

运行项目前我需要创建数据库表结构我使用默认数据库:

$ python manage.py migrate

Operations to perform:

Apply all migrations: admin, contenttypes, auth, sessions

Running migrations:

Applying contenttypes.0001_initial... OK

Applying auth.0001_initial... OK

Applying admin.0001_initial... OK

Applying sessions.0001_initial... OK

启服务:

$ python manage.py runserver

看面输:

Performing system checks...

System check identified no issues (0 silenced).

January 28, 2015 - 02:08:33

Django version 1.7.1, using settings 'mysite.settings'

Starting development server at

Quit the server with CONTROL-C.

端口8000启本服务器, 并且能台电脑连接访问 既服务器已经运行起现用网页浏览器访问 应该看令赏悦目淡蓝色 Django 欢迎页面始工作

指定启端口:

$ python manage.py runserver 8080

及指定 ip:

$ python manage.py runserver 0.0.0.0:8000

3. 创建 app

前面创建项目并且功运行现创建 app app 相于项目模块

项目目录创建 app:

$ python manage.py startapp polls

操作功 mysite 文件夹看已经叫 polls 文件夹目录结构:

polls

├── __init__.py

├── admin.py

├── migrations

│ └── __init__.py

├── models.py

├── tests.py

└── views.py

1 directory, 6 files

4. 创建模型

每 Django Model 都继承自 django.db.models.Model

Model 每属性 attribute 都代表 database field

通 Django Model API 执行数据库增删改查, 需要写些数据库查询语句

打 polls 文件夹 models.py 文件创建两模型:

import datetime

from django.db import models

from django.utils import timezone

class Question(models.Model):

question_text = models.CharField(max_length=200)

pub_date = models.DateTimeField('date published')

def was_published_recently(self):

return self.pub_date = timezone.now() - datetime.timedelta(days=1)

class Choice(models.Model):

question = models.ForeignKey(Question)

choice_text = models.CharField(max_length=200)

votes = models.IntegerField(default=0)

mysite/settings.py 修改 INSTALLED_APPS 添加 polls:

INSTALLED_APPS = (

'django.contrib.admin',

'django.contrib.auth',

'django.contrib.contenttypes',

'django.contrib.sessions',

'django.contrib.messages',

'django.contrib.staticfiles',

'polls',

)

添加新 app 我需要运行面命令告诉 Django 模型做改变需要迁移数据库:

$ python manage.py makemigrations polls

看面输志:

Migrations for 'polls':

0001_initial.py:

- Create model Choice

- Create model Question

- Add field question to choice

polls/migrations/0001_initial.py 查看迁移语句

运行面语句查看迁移 sql 语句:

$ python manage.py sqlmigrate polls 0001

输结:

BEGIN;

CREATE TABLE "polls_choice" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "choice_text" varchar(200) NOT NULL, "votes" integer NOT NULL);

CREATE TABLE "polls_question" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "question_text" varchar(200) NOT NULL, "pub_date" datetime NOT NULL);

CREATE TABLE "polls_choice__new" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "choice_text" varchar(200) NOT NULL, "votes" integer NOT NULL, "question_id" integer NOT NULL REFERENCES "polls_question" ("id"));

INSERT INTO "polls_choice__new" ("choice_text", "votes", "id") SELECT "choice_text", "votes", "id" FROM "polls_choice";

DROP TABLE "polls_choice";

ALTER TABLE "polls_choice__new" RENAME TO "polls_choice";

CREATE INDEX polls_choice_7aa0f6ee ON "polls_choice" ("question_id");

COMMIT;

运行面命令检查数据库否问题:

$ python manage.py check

再运行面命令创建新添加模型:

$ python manage.py migrate

Operations to perform:

Apply all migrations: admin, contenttypes, polls, auth, sessions

Running migrations:

Applying polls.0001_initial... OK

总结修改模型需要做几步骤:

修改 models.py 文件

运行 python manage.py makemigrations 创建迁移语句

运行 python manage.py migrate模型改变迁移数据库

阅读 django-admin.py documentation查看更 manage.py 用

创建模型我通 Django 提供 API 做测试运行面命令进入 python shell 交互模式:

$ python manage.py shell

面些测试:

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

# 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 输结 []我修改模型类使其输更易懂描述修改模型类:

from django.db import models

class Question(models.Model):

# ...

def __str__(self): # __unicode__ on Python 2

return self.question_text

class Choice(models.Model):

# ...

def __str__(self): # __unicode__ on Python 2

return self.choice_text

接继续测试:

from polls.models import Question, Choice

# Make sure our __str__() addition worked.

Question.objects.all()

[]

# Django provides a rich database lookup API that's entirely driven by

# keyword arguments.

Question.objects.filter(id=1)

[]

Question.objects.filter(question_text__startswith='What')

[]

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

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

# Make sure our custom method worked.

q = Question.objects.get(pk=1)

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

q.choice_set.create(choice_text='The sky', votes=0)

c = q.choice_set.create(choice_text='Just hacking again', votes=0)

# Choice objects have API access to their related Question objects.

c.question

# And vice versa: Question objects get access to Choice objects.

q.choice_set.all()

[, , ]

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)

[, , ]

# Let's delete one of the choices. Use delete() for that.

c = q.choice_set.filter(choice_text__startswith='Just hacking')

c.delete()

面部测试涉及 django orm 相关知识详细说明参考 DjangoORM

5. 管理 admin

Django优秀特性, 内置Django admin台管理界面, 便管理者进行添加删除网站内容.

新建项目系统已经我设置台管理功能见 mysite/settings.py:

INSTALLED_APPS = (

'django.contrib.admin', #默认添加台管理功能

'django.contrib.auth',

'django.contrib.contenttypes',

'django.contrib.sessions',

'django.contrib.messages',

'django.contrib.staticfiles',

'mysite',

)

同已经添加进入台管理 url, mysite/urls.py 查看:

url(r'^admin/', include(admin.site.urls)), #使用设置url进入网站台

接我需要创建管理用户登录 admin 台管理界面:

$ python manage.py createsuperuser

Username (leave blank to use 'june'): admin

Email address:

Password:

Password (again):

Superuser created successfully.

总结

看项目目录结构:

mysite

├── db.sqlite3

├── manage.py

├── mysite

│ ├── __init__.py

│ ├── settings.py

│ ├── urls.py

│ ├── wsgi.py

├── polls

│ ├── __init__.py

│ ├── admin.py

│ ├── migrations

│ │ ├── 0001_initial.py

│ │ ├── __init__.py

│ ├── models.py

│ ├── templates

│ │ └── polls

│ │ ├── detail.html

│ │ ├── index.html

│ │ └── results.html

│ ├── tests.py

│ ├── urls.py

│ ├── views.py

└── templates

└── admin

└── base_site.htm

通面介绍 django 安装、运行及何创建视 图模型清晰认识接深入习 django 自化测试、持久化、间件、 际 化等知识

结语:以上就是首席CTO笔记为大家介绍的关于django怎么设置usetz的全部内容了,希望对大家有所帮助,如果你还想了解更多这方面的信息,记得收藏关注本站。


本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:/Python/10213.html