Я пытаюсь создать веб-приложение, которое вводит данные с помощью ajax. Вход отправляется серверной стороне в Django, и мне нелегко получить правильное перенаправление URL-адреса. Я понимаю, что проблема на данный момент имеет отношение к приложению перевода django.Http302 Ответ при использовании Ajax для сообщения в Django view
См. Соответствующие разделы.
Ajax
$(document).ready(function(){
$('#applicant_form').on('submit', function(event){
event.preventDefault() //this will stop the file from submitting the form manually.
$.ajax({
url :'/save_applicant/', // the endpoint
type : "POST", // http method
data : { the_post : "Yay" }, // data sent with the post request
dataType: "json",
// handle a successful response
success : function(json) {
console.log("success"); // another sanity check
},
// handle a non-successful response
error : function(xhr,errmsg,err) {
$('#results').html("<div class='alert-box alert radius' data-alert>Oops! We have encountered an error: "+errmsg+
" <a href='#' class='close'>×</a></div>"); // add the error to the dom
console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console
}
});
});
});
HTML/DJANGO ШАБЛОНЫ
<form method = "POST" action = "" class="form bgform" id="applicant_form">
{% csrf_token %}
{{ applicant_form|crispy }}
<input class="btn btn-default" type="submit" name="Save" />
</form>
views.py
def save_applicant(request):
if request.method =='POST':
id = None
if 'applicant' in request.session:
id = request.session['applicant']
applicant_form = ApplicantForm(request.POST)
if applicant_form.is_valid():
session_applicant = applicant_form.save(commit=False)
if id:
session_applicant.id = id
else:
session_applicant.save()
request.session['applicant'] = session_applicant.id
return HttpResponse(json.dumps({'status':'applicant_saved'}), content_type='application/json')
else:
return HttpResponse(applicant_form.errors.as_json(),content_type='application/json')
else:
return HttpResponse(json.dumps({'status':'not_post'}),content_type='application/json')
urls.py
from django.conf.urls import include, url
from django.contrib import admin
from django.conf.urls.i18n import i18n_patterns
urlpatterns = [
]
urlpatterns += i18n_patterns(
url(r'^$', 'plan_b_profile.views.home', name='home'),
url(r'^save_applicant/','plan_b_profile.views.save_applicant',name='save_applicant'),
url(r'^admin/', include(admin.site.urls)),
)
командной строки
[21/Aug/2015 20:53:43]"POST /save_applicant HTTP/1.1" 302 0
[21/Aug/2015 20:53:43]"GET /en/save_applicant/ HTTP/1.1" 200 22 <---- HOW TO FIX THIS
Еще раз спасибо!
Разве что весь вид? – IanAuld
Что вы пытаетесь сделать? – skyline75489
эй я добавил полный обзор, извините, я не был уверен, что это было актуально. Я просто пытаюсь использовать ajax для POST для/save_applicant /. У меня есть перевод, хотя и вместо того, чтобы просто отправлять URL-адрес, как это обычно бывает, он меняет вызов GET и добавляет/en/save_applicant /. Не знаете, как это исправить, поэтому перенаправления не происходит. –