Django入门(二)

声明:本文是学习https://docs.djangoproject.com/zh-hans/2.2/文档后,笔者学后总结的精简板,适合快速入门,会引用上面的,想看完整板可以去上面的网址= ̄ω ̄=

Django视图:
在 Django 中,网页和其他内容都是从视图派生而来。每一个视图表现为一个简单的 Python 函数(或者说方法,如果是在基于类的视图里的话)。Django 将会根据用户请求的 URL 来选择使用哪个视图(更准确的说,是根据 URL 中域名之后的部分)。
在之前的基础上再添加更多的视图
主要先再应用/views.py中编写视图函数,再在urls中写路由,再在根目录URLconf中注册:
polls/views.py中添加:

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模块中添加路由:

from django.urls import path

from . import views

urlpatterns = [
    # ex: /polls/
    path('', views.index, name='index'),
    # ex: /polls/5/
    path('<int:question_id>/', views.detail, name='detail'),
    # ex: /polls/5/results/
    path('<int:question_id>/results/', views.results, name='results'),
    # ex: /polls/5/vote/
    path('<int:question_id>/vote/', views.vote, name='vote'),
]

重启服务后url输入http://127.0.0.1:8000/polls/1/vote/ 或者其他如detail,results后能看到创建的视图

视图的作用:
进行一些自定义的操作
返回被请求页面内的内容
插入html显示
主要用mysites中setting.py文件中的TEMPLATES配置项来修改载入和渲染的模板
在polls中创建templates目录,再创建一个目录 polls,然后在其中新建一个文件 index.html
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 %}

view.py

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

render()
之前返回网页的方法:载入模板,填充上下文,再返回由它生成的 HttpResponse 对象
这里可以直接用render1函数:

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)

抛出404
修改view,当没有问题的时候抛出404:

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/index.html

{{ question }}

简化函数 get_object_or_404()
去除模板中的硬编码URL
原来的index.html

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

改为

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

通过url()函数中的name来定义名字
为URL名称添加命名空间
在urls.py中加上app_name设置命名空间:

from django.urls import path

from . import views

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'),
]

index.html

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

Django 表单:
更新detail.html

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

{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}

<form action="{% url 'polls:vote' question.id %}" method="post">
{% csrf_token %}
{% for choice in question.choice_set.all %}
    <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}">
    <label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br>
{% endfor %}
<input type="submit" value="Vote">
</form>

urls.py中vote加一个name:

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

request.POST 是一个类字典对象,让你可以通过关键字的名字获取提交的数据。 这个例子中, request.POST[‘choice’] 以字符串形式返回选择的 Choice 的 ID。
如果在 request.POST[‘choice’] 数据中没有提供 choice , POST 将引发一个 KeyError
在增加 Choice 的得票数之后,代码返回一个 HttpResponseRedirect 而不是常用的 HttpResponse 、 HttpResponseRedirect 只接收一个参数:用户将要被重定向的 URL
在这个例子中,我们在 HttpResponseRedirect 的构造函数中使用 reverse() 函数。这个函数避免了我们在视图函数中硬编码 URL。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值