Форум сайта python.su
python3.4/django1.6
помогите пожалуйста отправить ajax-запрос из формы.
есть форма авторизации:
<form class="login_form" id="loginForm" action="#" method="post" novalidate="novalidate"> <input id="id_username" name="username" type="text"> <input id="id_password" name="password" type="password"> <input class="btn" type="submit" value="Войти"> </form>
"/accounts/ajax_username_check/" + $('#id_username').val()
http://site.ru/accounts/ajax_username_check/user1
url(r'accounts/ajax_username_check/(?P<username>.*)$', 'views.ajax_username_check', name='ajax_username_check'),
import os from django.conf import settings def ajax_username_check(request, username): with open(os.path.join(settings.BASE_DIR, "debug_local.txt"), "wb") as f: f.write(bytes(username, 'UTF-8')) result = False if request.is_ajax(): username_exist = User.objects.get(username=username) if(username_exist): result = username_exist return HttpResponse(result)
Офлайн
Вот так попробуйте
url(r'accounts/ajax_username_check/(?P<username>[a-zA-Z0-9-]+)/$', 'views.ajax_username_check', name='ajax_username_check'),
"/accounts/ajax_username_check/" + $('#id_username').val() + "/"
Офлайн
nnmware
debug_local.txt
Офлайн
Ну XNR запрос то отправляется? В инспекторе или firebug видно же.
К тому же вьюха дальше неправильно написана, если аякс- надо отдавать JSON
HttpResponse(json.dumps({'success': True}), content_type='application/json')
Офлайн
Посмотрите или корректно формируется URL.
Проверьте или запрос отправляется
Дальше уже смотрите что происходить во вюхе. Попробуйте воспользоваться командой pdb для дебагинга.
Офлайн
в общем всё заново переделал. осталась одна небольшая проблема. помогите пожалуйста решить её:
есть форма из 3 полей. код её не важен, поэтому не публикую. после клика по кнопке отправить я отменяю стандартное браузерное событие отправки формы и делаю аякс запрос:
$(".profile_form .btn_submit").click(function(event){ var phone = $('#id_phone').val(), skype = $('#id_skype').val(), other = $('#id_other').val(); event.preventDefault(); console.log(phone); console.log(skype); console.log(other); $.ajax({ url: "/change_profile/", type: 'POST', dataType:"html", data: { "phone": phone, "skype": skype, "other": other, "csrfmiddlewaretoken": $('#profile_form input[name=csrfmiddlewaretoken]').val() }, error: function() { //alert('Ошибка получения запроса'); }, success: function(data) { alert('ajax worked::' + '::' + data.message); //$('#mySmallModalLabel').text('Изменения сохранены'); //$('#infoModal').modal('show'); setTimeout(function(){ $('#infoModal').modal('hide'); }, 2000); } }); });
@login_required def change_profile(request): entry_user_profile = UserProfile.objects.get(user_ptr_id=request.user.id) form = ProfileForm(instance=entry_user_profile) if request.method == "POST" and request.is_ajax(): try: phone = request.POST.get('phone').strip() skype = request.POST.get('skype').strip() other = request.POST.get('other').strip() except: # to do pass else: form = ProfileForm(data=request.POST) if form.is_valid(): entry = UserProfile.objects.get(user_ptr_id=request.user.id) if phone: entry.phone = phone if skype: entry.skype = skype if other: entry.other = other entry.save() return HttpResponse({'message':'qwerty'}) t = loader.get_template('page_change_profile.html') c = RequestContext(request, { 'form': form, }, [custom_proc]) return HttpResponse(t.render(c))
alert('ajax worked::' + '::' + data.message);
ajax worked::undefined
ajax worked::message
Офлайн
return HttpResponse({'message':'qwerty'})
return HttpResponse(json.dumps({'message':'qwerty'}))
Офлайн
FishHook
return HttpResponse(json.dumps({'message':'qwerty'}))
POST http://localhost:8000/change_profile/ 500 (INTERNAL SERVER ERROR) jquery.2.min.js:6
x.support.cors.e.crossDomain.send jquery.2.min.js:6
x.extend.ajax jquery.2.min.js:6
(anonymous function) helper.js:14
x.event.dispatch jquery.2.min.js:5
y.handle
Офлайн
Попробуйте в ajax запросе указать datatype: json, также Вам правильно подсказали относительноHttpResponse(json.dumps({'message':'qwerty'})).
Офлайн
zlodiakРаз есть ошибка, то скорее всего есть респонз, в котором эта ошибка детализируется (при включенном DEBUG=True), вот например хром
так пробовал, но в консоль вот такая ошибка вываливается:
Офлайн