클라이언트의 HTML DOM을 서버에서 직접 다시 렌더링 할 수는 없습니다.
DjangoTemplate Engine을 통해 HTML 만 렌더링 한 다음 응답합니다. 즉 루트 요소를 업데이트하지 않으면 클라이언트의 DOM을 ajax로 업데이트 할 수 없습니다. <html>
. (이것은 페이지를 다시 불러오는 것과 같습니다!)
DOM 트리를 일부 데이터로 업데이트하려면 ajax 호출로 수행 한 다음 json
파일로만 업데이트하십시오. JsonResponse
을 사용하면 AJAX 응답 객체로 가져올 수 있습니다.
그럼 당신이해야 할 일은 장고 템플릿이 아니라 자바 스크립트 프로그래밍입니다. 당신의 views.py에서
, 다음과 같이 수행
# in your views.py
...
elif request.is_ajax():
product_id = request.POST.get('value')
if product_id:
product_info = Product.objects.get(id=product_id)
new_invoice_product = InvoiceProduct.objects.create(invoice_product_set=product_info)
invoice.attached_products.add(new_invoice_product)
context['attached_products'] = invoice.attached_products.all()
# return render(request, 'inventory/invoice_create.html', context) # NOT render but do like this:
return JsonResponse({
'new_data': {
'id': new_invoice_product.id
# and other informations you want...
}
})
당신의 HTML에서 다음과 같이 수행
<script src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
<script>
// in your HTML
// guessing you're using jquery..
$.ajax({
url: "test.html",
context: document.body
}).done(function (json) {
$('yourSelector').append(json['new_data']['id']);
});
</script>
는 기억이 코드는 단지 완전 작동하지 니펫 코드입니다. 당신이 더 예를 알고 싶다면, 링크를 한 번 봐 걸릴 :
https://simpleisbetterthancomplex.com/tutorial/2016/08/29/how-to-work-with-ajax-request-with-django.html
그럼 난 내 템플릿을 통해 반복하고있다 이해하고 있지 않다 문제를 이는 ManyToMany 필드 인 'attached_products'을 표시해야 특정 송장에 제품을 부착하는 내 송장 모델입니다. 아직도 그렇게 할 수 있을까요? –
개념은 간단합니다. "클라이언트 측에서 HTML을 다시 작성할 수 없습니다." django 템플릿 엔진은 서버 측 렌더링에서만 작동합니다. AJAX를 사용하면 작동하지 않습니다. 따라서 JS로 클라이언트 측 렌더링을 수행해야합니다. MTM 모델과 관련이 없습니다. 렌더링 된 HTML은 실제 '파이썬 모델'이 아닌 '문자열'입니다. – Beomi
알겠습니다. 내 질문이 계속 따라 잡기에 적합한 것 같니? –