PyCharm官方正版下载
本篇PyCharm使用教程将介绍在创建Django项目时如何创建 Django 模板??的相关内容?。
本篇PyCharm使用教程将介绍在创建Django项目时如何创建 Django 模板的相关内容
创建 Django 模板
from django.http import HttpResponse, HttpResponseRedirectfrom django.shortcuts import get_object_or_404, renderfrom django.urls import reversefrom .models import Question, Choicedef 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)def detail(request, question_id): question = get_object_or_404(Question, pk=question_id) return render(request, 'polls/detail.html', {'question': question})def results(request, question_id): question = get_object_or_404(Question, pk=question_id) return render(request, 'polls/results.html', {'question': question})def vote(request, question_id): question = get_object_or_404(Question, pk=question_id) try: selected_choice = question.choice_set.get(pk=request.POST['choice']) except (KeyError, Choice.DoesNotExist): return render(request, 'polls/detail.html', { 'question': question, 'error_message': "You didn't select a choice.", }) else: selected_choice.votes += 1 selected_choice.save() return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))
顺便提一下,帮助您创建导入语句的导入助手。
您注意到的第一件事是对页面index.html的未解决引用:

PyCharm 建议快速修复:如果单击灯泡或按Alt+Enter,则会在模板文件夹中创建相应的模板文件(请注意,PyCharm 还会创建该模板应驻留的目录polls ):

到目前为止,文件index.html是空的。向其中添加以下代码:
{% load staticfiles %}{% if latest_question_list %}
- {% for question in latest_question_list %}
- {{ question.question_text }} {% endfor %}
No polls are available.
{% endif %}注意模板文件中的代码完成!例如,当您键入开头时{%,PyCharm 会自动添加匹配的结尾%},将插入符 放在将来输入的位置。在 HTML 标记中,也可以使用代码完成。
注意分别出现在文件views.py和index.htmlhtml类型中的图标和图标:
这些图标使您可以立即在视图方法及其模板之间跳转。

PyCharm | 下载试用
JetBrains PyCharm是一种Python IDE,其带有一整套可以帮助用户在使用Python语言开发时提高其效率的工具。此外,该IDE提供了一些高级功能,以用于Django框架下的专业Web开发。
想要了解或购买PyCharm正版授权的朋友,欢迎咨询官方客服
PyCharm技术交流群:786598704 欢迎进群一起讨论
标签:
声明:本站部分文章及图片源自用户投稿,如本站任何资料有侵权请您尽早请联系jinwei@zod.com.cn进行处理,非常感谢!