Djangoæºç å¦ä¹ -15-SimpleTemplateResponse
Djangoç½ç»åºç¨å¼åç5项åºç¡æ ¸å¿ææ¯å æ¬æ¨¡åï¼Modelï¼ç设计ï¼URL ç设计ä¸é ç½®ï¼Viewï¼è§å¾ï¼çç¼åï¼Templateï¼æ¨¡æ¿ï¼ç设计åForm(表å)ç使ç¨ã
TemplateResponseä½ä¸ºæç»ä½¿ç¨çç±»ï¼é¤äºå¨åå§åæ¹æ³ä¸æ¥æ¶åæ°ç¶åä¼ éç»SimpleTemplateResponseåå§åæ¹æ³ä¹å¤ï¼å®å ¨æªéåSimpleTemplateResponseçå ¶å®æ¹æ³ã
继æ¿é¾:
HttpResponse --> SimpleTemplateResponse --> TemplateResponse
å¤å¶
â TemplateResponse 渲æ
TemplateResponseå¨è¿åå¨å®¢æ·ç«¯ä¹åï¼å·²ç»æ¸²æå®æï¼æ¸²æè¿ç¨å°æ¨¡æ¿åä¸ä¸æç»å转æ¢ä¸ºåèæµã
class TemplateResponse(SimpleTemplateResponse):
rendering_attrs = SimpleTemplateResponse.rendering_attrs + ['_request']
def __init__(self, request, template, context=None, content_type=None,
status=None, charset=None, using=None):
super().__init__(template, context, content_type, status, charset, using)
self._request = request
å¤å¶
以ä¸ä¸ç§æ åµï¼TemplateResponse被渲æ
1. æ¾å¼è°ç¨ render() æ¹æ³
2. æ¾å¼è°ç¨ content å±æ§
3. å¨ç©¿è¿æ¨¡æ¿ååºä¸é´ä»¶ä¹åï¼å¨ç©¿è¿ååºä¸é´ä»¶ä¹å
æ ¹æ®is_renderedå±æ§ç设置æºå¶ï¼ä¸ä¸ªTemplateResponseåªè½è¢«æ¸²æä¸æ¬¡ï¼ä¸è¿å½æç¡®å°ä¸ºcontentå±æ§èµå¼æ¶ï¼è¿äºæ¹åæ»ä¼è¢«åºç¨ã
å¦ææ³è¦å¼ºå¶éæ°æ¸²æï¼å°±æå¨ä¸ºcontentèµå¼ãç´æ¥èµå¼ä¸ä¼è°ç¨render()æ¹æ³ä¼è触åæ£æ¥is_renderedçé»è¾ï¼æ以è¿æ ·å¯ä»¥è¿è¡éæ°æ¸²æã
æ¹æ³
ä¼åç° TemplateResponse å SimpleTemplateResponse çæ¹æ³å¾ç¸ä¼¼ã
- TemplateResponse使ç¨ç»å®ç请æ±ï¼æ¨¡æ¿ï¼ä¸ä¸æï¼å 容类åï¼HTTPç¶æåå符éå®ä¾å对象ã
TemplateResponse.initï¼requestï¼templateï¼context = Noneï¼content_type = Noneï¼status = Noneï¼charset = Noneï¼using = Noneï¼
å¤å¶
- ä¸ä¸ªHttpRequestå®ä¾ã
request
å¤å¶
使ç¨ç¤ºä¾
from django.template.response import TemplateResponse
def index(request):
return TemplateResponse(request, 'article_list.html', {'articles': Articles.objects.all()})
å¤å¶
- ä¾èµäºå端ç模æ¿å¯¹è±¡ï¼ä¾å¦è¿åç对象 get_template()ï¼ï¼æ¨¡æ¿å称æ模æ¿å称å表ã
template
å¤å¶
- dict è¦æ·»å å°æ¨¡æ¿ä¸ä¸æçå¼çAãé»è®¤æ åµä¸ï¼è¿æ¯ä¸ä¸ªç©ºåå ¸ã
context = None
å¤å¶
- HTTP Content-Typeæ 头ä¸å å«çå¼ï¼å æ¬MIMEç±»åè§èåå符éç¼ç ãå¦æ content_typeæå®ï¼å使ç¨å ¶å¼ãå¦åï¼ DEFAULT_CONTENT_TYPE使ç¨ã
content_type = None
å¤å¶
- ååºçHTTPç¶æ代ç ã
status = None
å¤å¶
- å°å¯¹ååºè¿è¡ç¼ç çå符éãå¦æ没æç»åºï¼å®å°ä»ä¸æåcontent_typeï¼å¦æä¸æåï¼DEFAULT_CHARSETå°ä½¿ç¨è¯¥è®¾ç½®ã
charset = None
å¤å¶
- 该NAME模æ¿å¼æç使ç¨å è½½ç模æ¿ã
using = None
å¤å¶