Djangoæºç å¦ä¹ -14-JsonResponse
Djangoç½ç»åºç¨å¼åç5项åºç¡æ ¸å¿ææ¯å æ¬æ¨¡åï¼Modelï¼ç设计ï¼URL ç设计ä¸é ç½®ï¼Viewï¼è§å¾ï¼çç¼åï¼Templateï¼æ¨¡æ¿ï¼ç设计åForm(表å)ç使ç¨ã
TemplateResponseæä¾äºä¸ç§æ¹æ³ãä¸åºæ¬HttpResponse对象ä¸å ï¼TemplateResponse对象ä¿çè§å¾æä¾ç模æ¿åä¸ä¸æç详ç»ä¿¡æ¯ä»¥è®¡ç®ååºãå¨ååºè¿ç¨ä¸ç¨åéè¦æ¶ï¼ä¸ä¼è®¡ç®ååºçæç»è¾åºã
继æ¿é¾:
HttpResponse --> SimpleTemplateResponse --> TemplateResponse
å¤å¶
â SimpleTemplateResponse 对象
å±æ§
- SimpleTemplateResponse.template_name
è¦åç°ç模æ¿çå称ãæ¥åä¾èµäºå端ç模æ¿å¯¹è±¡ï¼ä¾å¦è¿åç对象 get_template()ï¼ï¼æ¨¡æ¿å称æ模æ¿å称å表ã
['index.html, 'path/to/header.html']
å¤å¶
- SimpleTemplateResponse.context_data
åç°æ¨¡æ¿æ¶è¦ä½¿ç¨çä¸ä¸ææ°æ®ãå®å¿ é¡»æ¯ä¸ä¸ª dictã
{'number': 123}
å¤å¶
- SimpleTemplateResponse.rendered_content
使ç¨å½å模æ¿åä¸ä¸ææ°æ®çååºå½ååç°å¼å 容ã
- SimpleTemplateResponse.is_rendered
ä¸ä¸ªå¸å°å¼ï¼æ示æ¯å¦å·²åç°ååºå 容ã
æ¹æ³
- åæ°çå«ä¹ä¸ HttpResponse ç¸åã
__init__(template, context=None, content_type=None, status=None, charset=None, using=None)
å¤å¶
- å¤çä¸ä¸æï¼æ¥æ¶dictç±»åçä¸ä¸æå 容ï¼é»è®¤è¿ååæ ·çdictï¼éåç¨ä»¥å®ç°å¯¹ä¸ä¸æåé¢å¤çå¤çã
resolve_context(context)
å¤å¶
- æ¥æ¶ç±(get_template()è¿åç)åå°ç¸å ³ç模æ¿å¯¹è±¡ï¼æ¨¡æ¿ååï¼æè å¤ä¸ªæ¨¡æ¿ååç»æçå表ã
resolve_template(template)
å¤å¶
- æ·»å 渲æå®æåçåè°å½æ°ï¼å¦æ该æ¹æ³è¿è¡æ¶æ¸²æå·²å®æï¼åè°å½æ°ä¼è¢«ç«å³è°ç¨ã
add_post_render_callback()
å¤å¶
- æ£æ¥is_renderedï¼è°ç¨rendered_contentå±æ§ï¼å¯å¨æ¸²æï¼å°å®ä¾çcontentå±æ§è®¾ç½®ä¸ºrendered_contentçå 容ï¼è°ç¨åè°å½æ°(å¦ææ)ï¼è¿åæç»ååºã该æ¹æ³ä» ä» å¨å次被è°ç¨æ¶çæ:é¦å æ£æ¥is_rendered,为Falseæä¼è¿è¡æ¸²æï¼å½æ¸²æåä¼å°is_renderd置为Trueã
render()
å¤å¶
TemplateResponseå¯ä»¥ç¨å¨ä»»ä½HttpResponseå¯ä»¥ä½¿ç¨çå°æ¹
from django.template.response import TemplateResponse
def index(request):
return TemplateResponse(request, 'article_list.html', {'articles': Articles.objects.all()})
å¤å¶