AJAX 및 jQuery로 django 양식을 게시하는 방법
나는 django AJAX 양식에 대한 수많은 튜토리얼을 확인했지만, 작업은 한 가지 방법을 알려주고, 어느 것도 한 가지 방법을 알려주고, 어느 것도 한 가지하지 않기 때문에 혼란 스럽습니다.
나는 "note"라는 모델, 그것을 때를위한 modelform을 가지고 있고, 템플릿 내부에서 노트 요소가 (jQuery Sortables에서) stop () 신호를 보낼마다 django가 객체를 업데이트해야합니다.
내 현재 코드 :
views.py
def save_note(request, space_name):
"""
Saves the note content and position within the table.
"""
place = get_object_or_404(Space, url=space_name)
note_form = NoteForm(request.POST or None)
if request.method == "POST" and request.is_ajax:
msg = "The operation has been received correctly."
print request.POST
else:
msg = "GET petitions are not allowed for this view."
return HttpResponse(msg)
자바 펼쳐 :
function saveNote(noteObj) {
/*
saveNote(noteObj) - Saves the notes making an AJAX call to django. This
function is meant to be used with a Sortable 'stop' event.
Arguments: noteObj, note object.
*/
var noteID = noteObj.attr('id');
$.post("../save_note/", {
noteid: noteID,
phase: "Example phase",
parent: $('#' + noteID).parent('td').attr('id'),
title: $('#' + noteID + ' textarea').val(),
message: "Blablbla",
});
}
현재 코드는 템플릿에서 데이터를 가져 오기 터미널에 인쇄합니다. 이 데이터를 어떻게 조작 할 수 있는지 모르겠습니다. 나는 어떤 사람들이 jqueryforms를 통해 데이터를 관리하여 데이터를 장고로 개인 것을 보았습니다.
AJAX에서 보낸 데이터에 액세스해야하고 노트를 업데이트해야합니까?
jQuery를 사용하고 있으므로 다음을 사용하지 않습니다.
<script language="JavaScript">
$(document).ready(function() {
$('#YOUR_FORM').submit(function() { // catch the form's submit event
$.ajax({ // create an AJAX call...
data: $(this).serialize(), // get the form data
type: $(this).attr('method'), // GET or POST
url: $(this).attr('action'), // the file to call
success: function(response) { // on success..
$('#DIV_CONTAINING_FORM').html(response); // update the DIV
}
});
return false;
});
});
</script>
편집하다
주석에서 지적했듯이, 위의 내용이 작동하지 않습니다. 따라서 다음을 시도하십시오.
<script type="text/javascript">
var frm = $('#FORM-ID');
frm.submit(function () {
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
$("#SOME-DIV").html(data);
},
error: function(data) {
$("#MESSAGE-DIV").html("Something went wrong!");
}
});
return false;
});
</script>
다음과 같이 변수 이름을 사용하여 POST 요청의 데이터에 액세스 할 수 있습니다.
request.POST["noteid"]
request.POST["phase"]
request.POST["parent"]
... etc
request.POST 객체는 없습니다. 변수에 값을 할당 한 다음 조작해야합니다.
이 JQuery 플러그인 을 사용 하는 것이 좋습니다 . 그러면 일반 HTML 양식을 다음 AJAX로 "업그레이드"할 수 있습니다. 코드의 모든 곳에 $ .post를 사용합니다.
또한 Firebug (Firefox 용) 또는 Google Chrome 용 개발자 도구의 네트워크보기를 사용하여 AJAX 호출에서 전송 된 내용을 볼 수 있습니다.
주의해야 할 점은 양식을 모달에 스니핑 된 html로 반환 할 때입니다.
Views.py
@require_http_methods(["POST"])
def login(request):
form = BasicLogInForm(request.POST)
if form.is_valid():
print "ITS VALID GO SOMEWHERE"
pass
return render(request, 'assess-beta/login-beta.html', {'loginform':form})
HTML을 반환하는 간단한보기
HTML Snipped 양식
<form class="login-form" action="/login_ajx" method="Post">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="header">Authenticate</h4>
</div>
<div class="modal-body">
{%if form.non_field_errors %}<div class="alert alert-danger">{{ form.non_field_errors }}</div>{%endif%}
<div class="fieldWrapper form-group has-feedback">
<label class="control-label" for="id_email">Email</label>
<input class="form-control" id="{{ form.email.id_for_label }}" type="text" name="{{ form.email.html_name }}" value="{%if form.email.value %}{{ form.email.value }}{%endif%}">
{%if form.email.errors %}<div class="alert alert-danger">{{ form.email.errors }}</div>{%endif%}
</div>
<div class="fieldWrapper form-group has-feedback">
<label class="control-label" for="id_password">Password</label>
<input class="form-control" id="{{ form.password.id_for_label }}" type="password" name="{{ form.password.html_name}}" value="{%if form.password.value %}{{ form.password.value }}{%endif%}">
{%if form.password.errors %}<div class="alert alert-danger">{{ form.password.errors }}</div>{%endif%}
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<input type="submit" value="Sign in" class="btn btn-primary pull-right"/>
</div>
</form>
모달이 포함 된 페이지
<div class="modal fade" id="LoginModal" tabindex="-1" role="dialog">{% include "assess-beta/login-beta.html" %}</div>
포함 태그를 사용하여 페이지로드시 스니핑을로드하면 모달을 열 때 사용할 수 있습니다.
Modal.js
$(document).on('submit', '.login-form', function(){
$.ajax({
type: $(this).attr('method'),
url: this.action,
data: $(this).serialize(),
context: this,
success: function(data, status) {
$('#LoginModal').html(data);
}
});
return false;
});
이 경우 .on ()을 사용하면 버튼이 아니라 문서에 제출 이벤트를 바인딩하는 키인 .live ()처럼 작동합니다.
다른 답변이 작동하므로 jQuery Form Plugin 사용하는 것을 선호합니다 . 그것은 당신이 원하는 것을 완벽하게 지원합니다. 포스트 뷰는 Django 부분에서 평소와 같이 처리되며 교체되는 HTML 만 반환합니다.
서버 측에서 django 코드는 다른 양식 제출을 처리하는 것과 동일한 방식으로 AJAX 게시물을 처리 할 수 있습니다. 예를 들면
views.py
def save_note(request, space_name):
"""
Saves the note content and position within the table.
"""
place = get_object_or_404(Space, url=space_name)
note_form = NoteForm(request.POST or None)
if request.method == "POST" and request.is_ajax():
print request.POST
if note_form.is_valid():
note_form.save()
msg="AJAX submission saved"
else:
msg="AJAX post invalid"
else:
msg = "GET petitions are not allowed for this view."
return HttpResponse(msg)
NoteForm이 ModelForm이라고 가정 했으므로 저장 방법이 있습니다. 참고 추가하는 것 외에도 것을 save()
명령을, 당신의 변경 request.is_ajax
에을 request.is_ajax()
(당신이 사용하는 경우 당신이 원하는, 이는 request.is_ajax
단지 요청라는 방법이 있는지 여부를 확인합니다 코드를 is_ajax
분명히는 않습니다).
공식 예제를 포함하여 Django 양식에서 AJAX POST를 사용하는 대부분의 예제 :
https://docs.djangoproject.com/en/1.9/topics/class-based-views/generic-editing/#ajax-example
ModelForm.clean()
오류가 발생하지 않으면 괜찮습니다 ( form_valid
). 그러나 그들은 어려운 부분을 수행하지 않습니다 : ModelForm
AJAX 응답을 통해 Javascript / DOM 클라이언트 측으로 오류를 번역 합니다.
플러그인 가능한 애플리케이션은 클라이언트 측 뷰 모델과 함께 AJAX 응답 라우팅을 사용 ModelForm
하여 기존 HTTP POST에서 표시되는 것과 유사한 클래스 기반보기 AJAX 포스트 유효성 검사 오류 를 자동으로 표시 합니다.
https://django-jinja-knockout.readthedocs.org/en/latest/forms.html#ajax-forms-processing https://django-jinja-knockout.readthedocs.org/en/latest/viewmodels.html
Jinja2와 Django 템플릿 엔진이 모두 지원됩니다.
참고 URL : https://stackoverflow.com/questions/7335780/how-to-post-a-django-form-with-ajax-jquery
'ProgramingTip' 카테고리의 다른 글
Python : ".. % (var) s .."% locals ()를 사용하는 것이 좋은 방법입니까? (0) | 2020.11.01 |
---|---|
Django : 게시물을 리디렉션하고 게시물 데이터를 전달하는 방법 (0) | 2020.11.01 |
std :: unique_ptr을 전달하는 방법은 무엇입니까? (0) | 2020.11.01 |
입력 파일이 아닌 리터럴 언어로 sed (0) | 2020.11.01 |
Swagger / OpenAPI- $ ref를 사용하여 가능한 정의 된 매개 변수 전달 (0) | 2020.11.01 |