Tools
首页
画图
音乐
采集
记事
博客
实验室
登录
lypeng
146
文章
11
分类
46
记事
分类
生活-[23]
Linux-[24]
前端-[9]
数据库-[16]
PHP-[31]
git-[7]
其他-[6]
python-[20]
算法-[4]
React-Native-[4]
中草药-[2]
广告位1
广告位2
首页
/ python
返回列表
django体验(二)跟着文档走 part3+part4
阅读:531
发布:2018-08-16
作者:lypeng
django体验 官方文档地址:`https://docs.djangoproject.com/en/2.1/intro/tutorial03/` [TOC] # 四、更多function与模板使用( part3) ## 1. 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) def detail(request,question_id): return HttpResponse("question id is %s." % question_id) ``` ## 2. urls.py新增如下 ``` path('
/', views.detail, name='detail'), # ex: /polls/5/results/ path('
/results/', views.results, name='results'), # ex: /polls/5/vote/ path('
/vote/', views.vote, name='vote'), ``` ## 3. templates polls/templates/polls/index.html ``` {% if latest_question_list %}
{% for question in latest_question_list %}
{{ question.question_text }}
{% endfor %}
{% else %}
No polls are available.
{% endif %} ``` ## 4. 修改views.py调用模板并渲染 有以下两种方式 ``` template = loader.get_template('polls/index.html') return HttpResponse(template.render(context, request)) ``` ``` from django.shortcuts import render ... def index(request): ... return render(request, 'polls/index.html', context) ``` ## 5.抛出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}) ``` detail.html ``` {{ question.id }}
{{ question.question_text }}
{{ question.pub_date }} ``` 更便捷方法get_object_or_404 `question = get_object_or_404(Question, pk=question_id)` 注意,这是个方法,传递两个参数 相似函数: `question_list = get_list_or_404(Question)`,还不清楚limit怎么传? ## 6.关闭debug设置 ``` DEBUG = False ALLOWED_HOSTS = ['127.0.0.1'] # 必须设置,否则报错 ``` 还是打开好,否则报个500错误,我都不知道是什么 ## 7.URL地址重定义 a.index.html 采用{% url 'detail' question.id %} 比/polls/{{ question.id }}/更灵活 b.polls/urls.py path('
/', views.detail, name='detail'), path的第一个参数可以自定义,而不用改模板与views ## 8.命名空间 urls.py新增app_name `app_name = 'polls'` index.html改写 `{% url 'polls:detail' question.id %}` ## 9.sqlite的查询与插入 和mysql一样,select insert  # 五、表单与自带的view(part4) amend 英 [ə'mend] 修正 generic 英 [dʒɪ'nerɪk] 公共的 来段广告: 360浏览器有道划词翻译插件,你值得拥有~ Ctrl+鼠标指一下即可翻译! use generic views less code is better write less do more ## 1. 表单与处理 detail.html,提交到vote方法 ```
{% csrf_token %} {% for choice in question.choice_set.all %}
{{ choice.choice_text }}
{% endfor %}
``` views.py vote方法处理用户提交 ``` 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,))) ``` ## 2.使用django自带的view a.修改urls.py的四个path ``` path('', views.IndexView.as_view(), name='index'), path('
/', views.DetailView.as_view(), name='detail'), path('
/results/', views.ResultsView.as_view(), name='results'), path('
/vote/', views.vote, name='vote') ``` b.修改views.py方法 ``` from django.http import HttpResponseRedirect from django.shortcuts import get_object_or_404, render from django.urls import reverse from django.views import generic from .models import Choice, Question class IndexView(generic.ListView): template_name = 'polls/index.html' context_object_name = 'latest_question_list' def get_queryset(self): return Question.objects.order_by('-pub_date')[:5] class DetailView(generic.DetailView): model = Question template_name = 'polls/detail.html' class ResultsView(generic.DetailView): model = Question template_name = 'polls/results.html' def vote(request, question_id): #not change ``` 访问,效果一样,但是这里面的东西,自带的一些属性、变量、方法等,需要记忆 >1.DetailView默认使用polls/question_detail.html,template_name自定义 >2.DetailView需要一个主键,命名为pk >3.context_object_name与get_queryset是自带的属性与方法
------本文结束
感谢阅读------
上一篇:
django体验(一)跟着文档走 part1+part2
下一篇:
django体验(三)跟着文档走 part6+part7