django超链接怎么设置(2023年最新整理)

作者&投稿:全要 (若有异议请与网页底部的电邮联系)
~

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

如何创建一个Django网站

本文演示如何创建一个简单的django网站,使用的django版本为1.7。

1.创建项目

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

$django-admin.pystartprojectmysite

创建后的项目目录如下:

mysite

├──manage.py

└──mysite

├──__init__.py

├──settings.py

├──urls.py

└──wsgi.py

1directory,5files

说明:

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

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

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

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

wsgi.py:WSGIweb应用服务器的配置文件。更多细节,查看HowtodeploywithWSGI

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

SITE_ID=1

LANGUAGE_CODE='zh_CN'

TIME_ZONE='Asia/Shanghai'

USE_TZ=True

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

$sudopipinstallpytz

2.运行项目

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

$pythonmanage.pymigrate

Operationstoperform:

Applyallmigrations:admin,contenttypes,auth,sessions

Runningmigrations:

Applyingcontenttypes.0001_initial...OK

Applyingauth.0001_initial...OK

Applyingadmin.0001_initial...OK

Applyingsessions.0001_initial...OK

然后启动服务:

$pythonmanage.pyrunserver

你会看到下面的输出:

Performingsystemchecks...

Systemcheckidentifiednoissues(0silenced).

January28,2015-02:08:33

Djangoversion1.7.1,usingsettings'mysite.settings'

Startingdevelopmentserverat

QuittheserverwithCONTROL-C.

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

你也可以指定启动端口:

$pythonmanage.pyrunserver8080

以及指定ip:

$pythonmanage.pyrunserver0.0.0.0:8000

3.创建app

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

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

$pythonmanage.pystartapppolls

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

polls

├──__init__.py

├──admin.py

├──migrations

│└──__init__.py

├──models.py

├──tests.py

└──views.py

1directory,6files

4.创建模型

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

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

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

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

importdatetime

fromdjango.dbimportmodels

fromdjango.utilsimporttimezone

classQuestion(models.Model):

question_text=models.CharField(max_length=200)

pub_date=models.DateTimeField('datepublished')

defwas_published_recently(self):

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

classChoice(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你的模型做了改变,需要迁移数据库:

$pythonmanage.pymakemigrationspolls

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

Migrationsfor'polls':

0001_initial.py:

-CreatemodelChoice

-CreatemodelQuestion

-Addfieldquestiontochoice

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

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

$pythonmanage.pysqlmigratepolls0001

输出结果:

BEGIN;

CREATETABLE"polls_choice"("id"integerNOTNULLPRIMARYKEYAUTOINCREMENT,"choice_text"varchar(200)NOTNULL,"votes"integerNOTNULL);

CREATETABLE"polls_question"("id"integerNOTNULLPRIMARYKEYAUTOINCREMENT,"question_text"varchar(200)NOTNULL,"pub_date"datetimeNOTNULL);

CREATETABLE"polls_choice__new"("id"integerNOTNULLPRIMARYKEYAUTOINCREMENT,"choice_text"varchar(200)NOTNULL,"votes"integerNOTNULL,"question_id"integerNOTNULLREFERENCES"polls_question"("id"));

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

DROPTABLE"polls_choice";

ALTERTABLE"polls_choice__new"RENAMETO"polls_choice";

CREATEINDEXpolls_choice_7aa0f6eeON"polls_choice"("question_id");

COMMIT;

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

$pythonmanage.pycheck

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

$pythonmanage.pymigrate

Operationstoperform:

Applyallmigrations:admin,contenttypes,polls,auth,sessions

Runningmigrations:

Applyingpolls.0001_initial...OK

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

修改models.py文件

运行pythonmanage.pymakemigrations创建迁移语句

运行pythonmanage.pymigrate,将模型的改变迁移到数据库中

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

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

$pythonmanage.pyshell

下面是一些测试:

frompolls.modelsimportQuestion,Choice#Importthemodelclasseswejustwrote.

#Noquestionsareinthesystemyet.

Question.objects.all()

[]

#CreateanewQuestion.

#Supportfortimezonesisenabledinthedefaultsettingsfile,so

#Djangoexpectsadatetimewithtzinfoforpub_date.Usetimezone.now()

#insteadofdatetime.datetime.now()anditwilldotherightthing.

fromdjango.utilsimporttimezone

q=Question(question_text="What'snew?",pub_date=timezone.now())

#Savetheobjectintothedatabase.Youhavetocallsave()explicitly.

q.save()

#NowithasanID.Notethatthismightsay"1L"insteadof"1",depending

#onwhichdatabaseyou'reusing.That'snobiggie;itjustmeansyour

#databasebackendpreferstoreturnintegersasPythonlonginteger

#objects.

q.id

1

#AccessmodelfieldvaluesviaPythonattributes.

q.question_text

"What'snew?"

q.pub_date

datetime.datetime(2012,2,26,13,0,0,775217,tzinfo=UTC)

#Changevaluesbychangingtheattributes,thencallingsave().

q.question_text="What'sup?"

q.save()

#objects.all()displaysallthequestionsinthedatabase.

Question.objects.all()

[Question:Questionobject]

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

fromdjango.dbimportmodels

classQuestion(models.Model):

#...

def__str__(self):#__unicode__onPython2

returnself.question_text

classChoice(models.Model):

#...

def__str__(self):#__unicode__onPython2

returnself.choice_text

接下来继续测试:

frompolls.modelsimportQuestion,Choice

#Makesureour__str__()additionworked.

Question.objects.all()

[Question:What'sup?]

#DjangoprovidesarichdatabaselookupAPIthat'sentirelydrivenby

#keywordarguments.

Question.objects.filter(id=1)

[Question:What'sup?]

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

[Question:What'sup?]

#Getthequestionthatwaspublishedthisyear.

fromdjango.utilsimporttimezone

current_year=timezone.now().year

Question.objects.get(pub_date__year=current_year)

Question:What'sup?

#RequestanIDthatdoesn'texist,thiswillraiseanexception.

Question.objects.get(id=2)

Traceback(mostrecentcalllast):

...

DoesNotExist:Questionmatchingquerydoesnotexist.

#Lookupbyaprimarykeyisthemostcommoncase,soDjangoprovidesa

#shortcutforprimary-keyexactlookups.

#ThefollowingisidenticaltoQuestion.objects.get(id=1).

Question.objects.get(pk=1)

Question:What'sup?

#Makesureourcustommethodworked.

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

#GivetheQuestionacoupleofChoices.Thecreatecallconstructsanew

#Choiceobject,doestheINSERTstatement,addsthechoicetotheset

#ofavailablechoicesandreturnsthenewChoiceobject.Djangocreates

#asettoholdthe"otherside"ofaForeignKeyrelation

#(e.g.aquestion'schoice)whichcanbeaccessedviatheAPI.

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

#Displayanychoicesfromtherelatedobjectset--nonesofar.

q.choice_set.all()

[]

#Createthreechoices.

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

Choice:Notmuch

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

Choice:Thesky

c=q.choice_set.create(choice_text='Justhackingagain',votes=0)

#ChoiceobjectshaveAPIaccesstotheirrelatedQuestionobjects.

c.question

Question:What'sup?

#Andviceversa:QuestionobjectsgetaccesstoChoiceobjects.

q.choice_set.all()

[Choice:Notmuch,Choice:Thesky,Choice:Justhackingagain]

q.choice_set.count()

3

#TheAPIautomaticallyfollowsrelationshipsasfarasyouneed.

#Usedoubleunderscorestoseparaterelationships.

#Thisworksasmanylevelsdeepasyouwant;there'snolimit.

#FindallChoicesforanyquestionwhosepub_dateisinthisyear

#(reusingthe'current_year'variablewecreatedabove).

Choice.objects.filter(question__pub_date__year=current_year)

[Choice:Notmuch,Choice:Thesky,Choice:Justhackingagain]

#Let'sdeleteoneofthechoices.Usedelete()forthat.

c=q.choice_set.filter(choice_text__startswith='Justhacking')

c.delete()

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

5.管理admin

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

新建的项目系统已经为我们设置好了后台管理功能,见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后台管理界面:

$pythonmanage.pycreatesuperuser

Username(leaveblanktouse'june'):admin

Emailaddress:

Password:

Password(again):

Superusercreatedsuccessfully.

总结

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

mysite

├──db.sqlite3

├──manage.py

├──mysite

│├──__init__.py

│├──settings.py

│├──urls.py

│├──w


禄丰县13545379837: 怎么设置超连接
纵婷邦莱: 在网页编辑窗口中,单击要设置为超链接的图片代码.2、单击常用工具栏中的“超链接”按钮,在弹出的“创建超链接”对话框中,设置超链接的目标,最后单击"确定"按钮.

禄丰县13545379837: 图像插上超链接后,border如何设置? -
纵婷邦莱: 1、首先打开意图软件.2、选中你要插入超链接的内容.3、单击插入选项'.4、选中超链接选项然后单击插入超链接按钮.5、选择超链接类型如internet.6、输入超链接地址然后单击确定按钮.7、此时即可看到内容右上侧有一个IE标志,单击即可访问超链接地址.

禄丰县13545379837: 网页怎样设置超链接 -
纵婷邦莱: 可以用以下的方法来插入超级链接: 1、 在属性面板的相应位置来设置插入的链接. 2、 使用指向来链接(小滚轮),这种方法只可以链接到本地,在“文件”面板中能够看到的文件. 3、 把想要进行链接的文字选中,按住键盘上“shift”键的...

禄丰县13545379837: 如何安装配置Django环境 -
纵婷邦莱: 一、安装Django 1. 通过pip安装Django 如果你是通过升级的方式安装Django,那么你需要先卸载旧的版本. Django提供3种发行版本,推荐使用官方的稳定版本:你的操作系统提供的发行版本(Linux) 官方稳定版本(推荐) 开发测试版本 ...

禄丰县13545379837: 如何创建超链接? -
纵婷邦莱: 选中你要设置超链接的文字或者图片,然后右键 在右键菜单里选择"超链接"菜单,在弹出的"插入超链接"对话框里就可以设置超链接了 这个超链接可以设置为网络上的网页,也可以设置为本地的某个文件

禄丰县13545379837: 幻灯片中如何弄超连接
纵婷邦莱: 对着你要设置超链接的文字或图片右键,选择“动作设置”,再选择“超链接到~~”一项就可以设置了

禄丰县13545379837: 幻灯片如何设置超链接? -
纵婷邦莱: 选中要设置超链接的图片或文字,右键菜单里选【超链接到】(也可以点击菜单栏里的“插入”------“超链接”),接下来出现要你选择要链接什么的对话框,在这个对话框里选定一个要链接的幻灯片或你电脑上的其他文件或软件,也可以是一个网址.选好以后,点击“确定”插入完成.

禄丰县13545379837: linux下怎么安装django -
纵婷邦莱: 第一步安装Django:下载包:Django-0.96.1.tar.gz 解压这个包:tar zxf Django-0.96.1.tar.gz -C/usr/tmp 安装:cd /usr/tmp cd Django-0.96.1 su python setup.py install 检查安装是否正确:python>>> import django>>> django.VERSION(0, 96....

禄丰县13545379837: Excel2003里超级链接怎样设置
纵婷邦莱: 点击文件上方的插入,然后在最末那里找到超链接,点击后会出现1个窗口,按实际情况来做就能够.

禄丰县13545379837: 制作网页时,怎样设置超链接?
纵婷邦莱: ,所谓的超链接是指从一个网页指向一个目标的连接关系,这个目标可以是另一个网页,也可以是相同网页上的不同位置,还可以是一个图片,一个电子邮件地址,一个文件,甚至是一个应用程序.而在一个网页中用来超链接的对象,可以是一段...

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 星空见康网