Ajax 호출 후 Django 템플릿을 사용하여 JSON 객체 렌더링
Django 에서 Ajax 를 수행하는 최적의 방법이 무엇인지 이해하려고 노력해 왔습니다 . 여기저기서 내용을 읽음으로써 일반적인 프로세스는 다음과 같습니다.
JavaScript 라이브러리 (예 : jQuery )를 사용하여 Ajax 호출을 공식화 하고 Django에서 호출을 잡아서보기 함수에 전달하는 URL 패턴을 설정합니다.
에 파이썬 보기 기능에 관심이 개체를 검색하고 JSON 형식 또는 유사한의 클라이언트로 다시 보내 (사용하여 시리얼 모듈 또는 내장 simplejson )
JSON 데이터를 수신하고 파싱하는 콜백 함수를 JavaScript에 정의하여 표시되는 데 필요한 HTML을 생성합니다. 마지막으로 자바 스크립트 스크립트는 HTML을 어디에 두어야합니다.
자, 내가 아직도 얻지 못하는 것은 Django 템플릿이이 모든 것과 어떻게 관련되어 있습니까? 분명히 우리는 템플릿의 힘을 전혀 사용하지 않고 있습니다. 이상적으로는 데이터가 반복되고 HTML 블록이 생성되도록 JSON 객체와 템플릿 이름을 다시 전달하는 것이 좋을 것이라고 생각했습니다. 하지만 내가 여기서 완전히 틀렸을 수도 있습니다 ...
이 방향으로가는 유일한 리소스는 이 스 니펫 (769) 이지만 아직 시도하지 않았습니다. 분명히이 경우에 일어날 일은 모든 결과 HTML이 서버 측에서 생성 된 다음 클라이언트로 전달된다는 것입니다. JavaScript 콜백 함수는 올바른 위치에만 표시하면됩니다.
이로 인해 성능 문제가 발생합니까? 그렇지 않다면 위의 스 니펫을 사용하지 않아도 프론트 엔드 대신 Python을 사용하여 백엔드에서 직접 HTML 형식을 지정하지 않는 이유는 무엇입니까?
감사합니다!
업데이트 : 위 버전의 향상된 버전이므로 snippet 942 를 사용하세요 ! 상속 지원이이 방식으로 훨씬 더 잘 작동한다는 것을 알았습니다 ..
안녕하세요 바이킹 고 세군도 감사합니다!
나도 데코레이터를 사용하는 것을 좋아한다 :-). 그러나 그 동안 나는 위에서 언급 한 스 니펫에서 제안한 접근 방식을 따르고 있습니다. 단, 스 니펫 n을 대신 사용 하십시오. 942 는 원래 버전의 개선 된 버전이기 때문입니다. 작동 방식은 다음과 같습니다.
재사용 할 수있는 유용한 블록을 포함하는 크기에 관계없이 템플릿 (예 : 'subtemplate.html')이 있다고 가정 해보십시오.
........
<div id="results">
{% block results %}
{% for el in items %}
<li>{{el|capfirst}}</li>
{% endfor %}
{% endblock %}
</div><br />
........
뷰 파일에서 위의 스 니펫을 가져 오면 템플릿의 모든 블록을 쉽게 참조 할 수 있습니다. 멋진 기능은 템플릿 간의 상속 관계를 고려하는 것이므로 다른 블록 등을 포함하는 블록을 참조하면 모든 것이 잘 작동합니다. 따라서 ajax-view는 다음과 같습니다.
from django.template import loader
# downloaded from djangosnippets.com[942]
from my_project.snippets.template import render_block_to_string
def ajax_view(request):
# some random context
context = Context({'items': range(100)})
# passing the template_name + block_name + context
return_str = render_block_to_string('standard/subtemplate.html', 'results', context)
return HttpResponse(return_str)
다음은 기존 렌더링과 Ajax 응답 렌더링에 동일한 템플릿을 사용하는 방법입니다.
주형:
<div id="sortable">
{% include "admin/app/model/subtemplate.html" %}
</div>
포함 된 템플릿 (일명 : 하위 템플릿) :
<div id="results_listing">
{% if results %}
{% for c in results %}
.....
{% endfor %}
{% else %}
Ajax보기 :
@login_required
@render_to('admin/app/model/subtemplate.html')#annoying-decorator
def ajax_view(request):
.....
return {
"results":Model.objects.all(),
}
물론 render_to_response를 사용할 수 있습니다. 하지만 나는 그 성가신 데코레이터를 좋아합니다 : D
Ajax를 사용하여 렌더링 된 HTML 비트를 반환 할 수없고 원하는 지점에 기존 페이지에 삽입 할 수없는 이유는 없습니다. 원한다면 Django의 템플릿을 사용하여이 HTML을 렌더링 할 수 있습니다.
Ajax를 할 때 템플릿을 사용하지 않는다고 생각합니다. 템플릿은 서버 측에서 동적 HTML을 쉽게 생성 할 수 있도록 존재하므로 HTML 내부에 프로그래밍 후크를 거의 제공하지 않습니다.
Ajax의 경우 JSON 데이터를 전달하고 Python에서 원하는대로 형식을 지정할 수 있습니다. HTML / 문서 요소는 클라이언트 측의 jQuery와 같은 일부 JavaScript 라이브러리에 의해 JSON을 사용하여 클라이언트 측에서 생성됩니다.
Maybe if you have a very specific case of replacing some inner HTML from server side HTML then maybe you can use templates but in that case why you would need JSON? You can just query the HTML page via Ajax and change inner or outer or whatever HTML.
Templates are for the purpose of presentation. Responding with data in format X (JSON, JSONP, XML, YAML, *ml, etc.) is not presentation, so you don't need templates. Just serialize your data into format X and return it in an HttpResponse.
While templates are indeed just for presentation purposes, it shouldn't matter if you are doing it on the serverside or client side. It all comes down to separating the control logic that is performing an action, from the view logic that is just responsible for creating the markup. If your javascript control logic is having to handle how you are rendering or displaying the HTML, then you might be doing it wrong, but if you isolate that rendering logic to another object or function, and just passing it the data necessary for the render, then you should be fine; it mirrors how we separate our controllers, models and views on the server side.
Take a look at the github project: http://github.com/comolongo/Yz-Javascript-Django-Template-Compiler
It compiles django templates into optimized javascript functions that will generate your presentation html with data that you pass it. The compiled functions are in pure javascript, so there are no dependencies on other libraries. Since the templates are compiled instead of being parsed at runtime, the strings and variables are all already placed into javascript strings that just need to be concatenated, so you get a huge speed increase compared to techniques that require you to do dom manipulation or script parsing to get the final presentation. Right now only the basic tags and filters are there, but should be enough for most things, and more tags will be added as people start making requests for them or start contributing to the project.
You can use jquery.load()
or similar, generating the HTML on the server and loading it into the DOM with JavaScript. I think someone has called this AJAH.
Unfortunately, Django templates are designed to be executed server side only. There is at least one project to render Django templates using Javascript, but I haven't used it and so I don't know how fast, well supported or up to date it is. Other than this, you have to either use the Django templates on the server or generate dynamic elements on the client without using templates.
'IT Share you' 카테고리의 다른 글
Angular2 이벤트는 어떤 Typescript 유형입니까? (0) | 2020.11.18 |
---|---|
easy_install for Python과 같은 Java 용 패키지 관리자가 있습니까? (0) | 2020.11.18 |
Python 3이 이전 버전과 호환되지 않는 이유는 무엇입니까? (0) | 2020.11.18 |
Jekyll을 사용한 로컬 포스트 자산 (0) | 2020.11.18 |
Eclipse에서 열려있는 모든 파일을 검색하는 방법은 무엇입니까? (0) | 2020.11.18 |