Django 入门学习总结4

视图是Django应用程序在Python语言中提供特定的方法并对应于有特定的模板的网页。网页的页面通过视图的方式进行跳转。

在投票系统中,有四个视图:

  • 首页视图,显示最新的问题列表。
  • 细节视图,显示问题文本,通过表单可以提交问题。
  • 结果视图,显示问题和对应的结果。
  • 投票跳转,管理一个问题对应于一个选项的投票跳转页面。

1、视图的产生

修改polls/views.py文件,增加视图相关内容。

from django.shortcuts import render

from django.http import HttpResponse

def index(request):

return HttpResponse("Hello, world. You're at the polls index.")

def detail(request, question_id):

return HttpResponse("You're looking at question %s." % question_id)

def results(request, question_id):

response = "You're looking at the results of question %s."

return HttpResponse(response % question_id)

def vote(request, question_id):

return HttpResponse("You're voting on question %s." % question_id)

将这些视图信息添加到polls/urls.py文件中,以便跳转时使用。

在地址栏中输入:

http://127.0.0.1:8000/polls/34/

则在页面中显示:

You're looking at question 34.

输入http://127.0.0.1:8000/polls/34/results/,则显示:

You're looking at the results of question 34.

2、使用视图完成相应的工作

每个视图会返回包含的内容或输出异常。

修改polls/views.py文件,以便显示更详细的信息。

from django.http import HttpResponse

from .models import Question

def index(request):

latest_question_list = Question.objects.order_by("-pub_date")[:5]

output = ", ".join([q.question_text for q in latest_question_list])

return HttpResponse(output)

这种方式为硬代码方式,每次修改网页的内容,需要修改Python代码。

可以通过模板的方式来显示网页的内容。

第一步,在polls中创建templates文件夹,Django会自动地从这个文件夹中寻找模板文件。在templates文件夹中创建polls文件夹,如下图所示。

新建polls/templates/polls/index.html文件,并在文件中添加以下内容:

{% if latest_question_list %}

<ul>

{% for question in latest_question_list %}

<li><a href="/polls/{{ question.id }}/">{{ question.question_text }}</a></li>

{% endfor %}

</ul>

{% else %}

<p>No polls are available.</p>

{% endif %}

更新polls/views.py文件中的index方法:

from django.http import HttpResponse

from django.template import loader

from .models import Question

def index(request):

latest_question_list = Question.objects.order_by("-pub_date")[:5]

template = loader.get_template("polls/index.html")

context = {

"latest_question_list": latest_question_list,

}

return HttpResponse(template.render(context, request))

这个方法将调用模块页面,并输出内容。这时再输入地址:

http://127.0.0.1:8000/polls/

将会显示投票系统列表页面。

Django提供了另一种快捷的方式,功能是一样的:

from django.shortcuts import render

from .models import Question

def index(request):

latest_question_list = Question.objects.order_by("-pub_date")[:5]

context = {"latest_question_list": latest_question_list}

return render(request, "polls/index.html", context)

3、处理404错误

继续修改polls/views.py文件如下:

from django.http import Http404

from django.shortcuts import render

from .models import Question

...

def detail(request, question_id):

try:

question = Question.objects.get(pk=question_id)

except Question.DoesNotExist:

raise Http404("Question does not exist")

return render(request, "polls/detail.html", {"question": question})

新建polls/templates/polls/detail.html文件内容如下:

4、使用模块系统

修改polls/templates/polls/detail.html内容为:

<h1>{{ question.question_text }}</h1>

<ul>

{% for choice in question.choice_set.all %}

<li>{{ choice.choice_text }}</li>

{% endfor %}

</ul>

5、在模板中清除硬代码内容

修改polls/index.html内容:

<li><a href="{% url 'detail' question.id %}">{{ question.question_text }}</a></li>

6、URL命名空间的命名

在polls/urls.py文件中,添加一行语句:

app_name = "polls"

。。。

app_name = "polls"

urlpatterns = [

path("", views.index, name="index"),

path("<int:question_id>/", views.detail, name="detail"),

path("<int:question_id>/results/", views.results, name="results"),

path("<int:question_id>/vote/", views.vote, name="vote"),

]

修改polls/templates/polls/index.html文件中的内容为:

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

以体现命名空间的效果,最后的显示效果是一样的。

相关推荐
moxiaoran57531 小时前
uni-app学习笔记二十九--数据缓存
笔记·学习·uni-app
AI蜗牛之家1 小时前
Qwen系列之Qwen3解读:最强开源模型的细节拆解
人工智能·python
whyeekkk2 小时前
python打卡第48天
开发语言·python
pop_xiaoli3 小时前
OC—UI学习-2
学习·ui·ios
Lin Hsüeh-ch'in3 小时前
Vue 学习路线图(从零到实战)
前端·vue.js·学习
恰薯条的屑海鸥4 小时前
零基础在实践中学习网络安全-皮卡丘靶场(第十五期-URL重定向模块)
学习·安全·web安全·渗透测试·网络安全学习
Eiceblue4 小时前
Python读取PDF:文本、图片与文档属性
数据库·python·pdf
weixin_527550404 小时前
初级程序员入门指南
javascript·python·算法
程序员的世界你不懂4 小时前
Appium+python自动化(十)- 元素定位
python·appium·自动化
CryptoPP5 小时前
使用WebSocket实时获取印度股票数据源(无调用次数限制)实战
后端·python·websocket·网络协议·区块链