Уведомления

Группа в Telegram: @pythonsu

#1 Авг. 8, 2012 19:17:38

UsCr
От:
Зарегистрирован: 2009-11-04
Сообщения: 216
Репутация: +  0  -
Профиль   Отправить e-mail  

dajaxice и 403 ошибка

Здравствуйте! Решил поиграться с ajax'ом. Использую dajaxice. Повторил пример отсюда: django-ru.blogspot.com. Нажимаю кнопочку - получаю алерт: “Something goes wrong”. В логах вебсервера при этом: “POST /dajaxice/ajax.primer/ HTTP/1.1” 403 2282

Гугл говорит, что ошибка распространённая. Но вот решение всегда у всех разное. Никто с таким не сталкивался? Так как же решается такая проблема?



Офлайн

#2 Авг. 8, 2012 21:32:48

adw0rd
От: Санкт-Петербург
Зарегистрирован: 2012-07-28
Сообщения: 107
Репутация: +  8  -
Профиль   Отправить e-mail  

dajaxice и 403 ошибка

Там явно 403. А вы можете посмотреть что именно отвечает веб-сервер, допустим через Firebug?




Python, Django, Flask, Git, Emacs, Nginx, MySQL, SphinxSearch, Redis, Linux, FreeBSD
Мой блог, я на GitHub

Офлайн

#3 Авг. 9, 2012 09:35:50

Chern
От: Киев
Зарегистрирован: 2010-09-15
Сообщения: 71
Репутация: +  3  -
Профиль   Отправить e-mail  

dajaxice и 403 ошибка

Скорее всего проблема в отсутствии csrfmiddlewaretoken

Cross Site Request Forgery protection



Офлайн

#4 Авг. 9, 2012 10:51:36

UsCr
От:
Зарегистрирован: 2009-11-04
Сообщения: 216
Репутация: +  0  -
Профиль   Отправить e-mail  

dajaxice и 403 ошибка

Chern
Скорее всего проблема в отсутствии csrfmiddlewaretoken
пробовал:

Добавил django.middleware.csrf.CsrfViewMiddleware в MIDDLEWARE_CLASSES. В шаблоне сделал так:
<input onclick=“Dajaxice.ajax.primer(primer_callback,{'message':'test'});” type=“button” value=“Push Me!”>{% csrf_token %}

Ничего не меняется…

adw0rd
Там явно 403. А вы можете посмотреть что именно отвечает веб-сервер, допустим через Firebug?

name: :8080/dajaxice/ajax.primer/ path: /dajaxice/ajax.primer Method: POST Status: 403 FORBIDDEN



Офлайн

#5 Авг. 9, 2012 12:09:42

adw0rd
От: Санкт-Петербург
Зарегистрирован: 2012-07-28
Сообщения: 107
Репутация: +  8  -
Профиль   Отправить e-mail  

dajaxice и 403 ошибка

Круто, а может на сервере включить DEBUG=True? Или логи посмотреть?

Добавил django.middleware.csrf.CsrfViewMiddleware в MIDDLEWARE_CLASSES. В шаблоне сделал так: <input onclick=“Dajaxice.ajax.primer(primer_callback,{'message':'test'});” type=“button” value=“Push Me!”>{% csrf_token %}

Ничего не меняется…

А Dajaxice точно сабмитит "csrfmiddlewaretoken"?




Python, Django, Flask, Git, Emacs, Nginx, MySQL, SphinxSearch, Redis, Linux, FreeBSD
Мой блог, я на GitHub

Офлайн

#6 Авг. 9, 2012 17:36:14

UsCr
От:
Зарегистрирован: 2009-11-04
Сообщения: 216
Репутация: +  0  -
Профиль   Отправить e-mail  

dajaxice и 403 ошибка

adw0rd
Круто, а может на сервере включить DEBUG=True? Или логи посмотреть?
Дебаг включён. Оно не выкидывает меня на страничку с ошибкой.


adw0rd
А Dajaxice точно сабмитит “csrfmiddlewaretoken”?

Откровенно говоря, я не очень представляю себе, что такое csrfmiddlewaretoken. Но в гугле есть варианты решения как раз с добавлением {% csrf_token %}. У меня не прокатило.



Офлайн

#7 Авг. 9, 2012 18:52:29

adw0rd
От: Санкт-Петербург
Зарегистрирован: 2012-07-28
Сообщения: 107
Репутация: +  8  -
Профиль   Отправить e-mail  

dajaxice и 403 ошибка

Ну вы посмотрите в Firebug, Live HTTP Headers и т.п. Какие POST данные уходят на сервер




Python, Django, Flask, Git, Emacs, Nginx, MySQL, SphinxSearch, Redis, Linux, FreeBSD
Мой блог, я на GitHub

Офлайн

#8 Авг. 13, 2012 12:06:55

UsCr
От:
Зарегистрирован: 2009-11-04
Сообщения: 216
Репутация: +  0  -
Профиль   Отправить e-mail  

dajaxice и 403 ошибка

adw0rd
Ну вы посмотрите в Firebug, Live HTTP Headers и т.п. Какие POST данные уходят на сервер

Уходит такой запрос:

Parameters application/x-www-form-urlencoded argv{“message”:“test”}
Source argv=%7B%22message%22%3A%22test%22%7D

А вот в ответ, оказывается, приходит кроме 403 ошибки, ещё и HTML с инструкциями. Вот что там есть:

Forbidden (403)
CSRF verification failed. Request aborted.
Help
Reason given for failure:
    CSRF cookie not set.
    
In general, this can occur when there is a genuine Cross Site Request Forgery, or when Django's CSRF mechanism has not been used correctly. For POST forms, you need to ensure:
Your browser is accepting cookies.
The view function uses RequestContext for the template, instead of Context.
In the template, there is a {% csrf_token %} template tag inside each POST form that targets an internal URL.
If you are not using CsrfViewMiddleware, then you must use csrf_protect on any views that use the csrf_token template tag, as well as those that accept the POST data.
You're seeing the help section of this page because you have DEBUG = True in your Django settings file. Change that to False, and only the initial error message will be displayed.
You can customize this page using the CSRF_FAILURE_VIEW setting.

Я ведь всё это проделал, но…

Прошу помощи, самому не раскопаться. Показываю код:

settings.py:
# Django settings for iptvmon project.
DEBUG = True
TEMPLATE_DEBUG = DEBUG
DAJAXICE_DEBUG = True
DAJAXICE_MEDIA_PREFIX = "dajaxice"
DAJAXICE_FUNCTIONS = (
        'ajax.ajax.primer',
         )
ADMINS = (
    # ('Your Name', 'your_email@domain.com'),
)
MANAGERS = ADMINS
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': 'iptvmonitor',                      # Or path to database file if using sqlite3.
        'USER': 'iptv',                      # Not used with sqlite3.
        'PASSWORD': 'iptv',                  # Not used with sqlite3.
        'HOST': '',                      # Set to empty string for localhost. Not used with sqlite3.
        'PORT': '',                      # Set to empty string for default. Not used with sqlite3.
    }
}
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# On Unix systems, a value of None will cause Django to use the same
# timezone as the operating system.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'America/Chicago'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale
USE_L10N = True
# Absolute path to the directory that holds media.
# Example: "/home/media/media.lawrence.com/"
MEDIA_ROOT = ''
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash if there is a path component (optional in other cases).
# Examples: "http://media.lawrence.com", "http://example.com/media/"
MEDIA_URL = ''
# URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a
# trailing slash.
# Examples: "http://foo.com/media/", "/media/".
STATIC_URL = '/media/'
# Make this unique, and don't share it with anybody.
SECRET_KEY = 'b!$(on@y%9#uh3ld@dovgcy=$0qirs$(e5o@c%2*#t8f8#hfco'
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.Loader',
    'django.template.loaders.app_directories.Loader',
    'django.template.loaders.eggs.Loader',
)
MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
)
ROOT_URLCONF = 'iptvmon.urls'
TEMPLATE_DIRS = (
    "/root/iptv_monitor/front/iptvmon/templates",
    # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
)
INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    # Uncomment the next line to enable the admin:
    # 'django.contrib.admin',
    # Uncomment the next line to enable admin documentation:
    # 'django.contrib.admindocs',
    'iptvmon.iptvmonitor',
    'dajaxice', 
    'dajax', 
)

urls.py:
from django.conf.urls.defaults import *
from iptvmon.views import *
from django.conf import settings
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = patterns('',
    ('^$', index),
    ('^update/all/(\d{1})$', update_all),
    ('^update/(\d+)$', update_channel),
    ('^update/group/(\d+)$', update_group),
    ('^b/$', display_meta),
    (r'^%s/' % settings.DAJAXICE_MEDIA_PREFIX, include('dajaxice.urls')),
)

views.py основного приложения:
# -*- coding=utf-8 -*- #
from django.template.loader import get_template
from django.http import HttpResponse
from iptvmonitor.models import Channels as ch
from django.template import Context, Template
from iptv_checker import *
from django.http import HttpResponseRedirect
from django.utils import simplejson
from dajaxice.core import dajaxice_functions
from django.core.context_processors import csrf
def index(request):
    c = {}
    c.update(csrf(request))
    t = get_template('index.html')
    html = t.render(Context({'channels': ch.objects.all().order_by('id'), 'host':request.get_host(), 'update_all':0}))
    return HttpResponse(html, c)
...
def primer(request,message):
    return_message=u'Полученное сообщение: {0}'.format(message)
    return simplejson.dumps({'message':return_message})

vievs.py приложения, которое реализует ajax:
from django.template.loader import get_template
from django.http import HttpResponse
from iptvmonitor.models import Channels as ch
from django.template import Context, Template
from iptv_checker import *
from django.http import HttpResponseRedirect
from django.utils import simplejson
from dajaxice.core import dajaxice_functions
from django.core.context_processors import csrf
def primer(request,message):
    return_message=u'Полученное сообщение: {0}'.format(message)
    return simplejson.dumps({'message':return_message})

index.html:
<html>
<head>
<title>IPTV monitor
</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<form action="." method="POST">{% csrf_token %}
<input onclick="Dajaxice.ajax.primer(primer_callback,{'message':'test'});" type="button" value="Push Me!">
</form>
{% dajaxice_js_import %}
<script type="text/javascript">
function primer_callback(data){
    if(data!=Dajaxice.EXCEPTION){
        alert(data.message);
    }else{
        alert('Error');
    }
}
</script>
...дальше ничего интересного...



Офлайн

#9 Авг. 13, 2012 12:43:44

adw0rd
От: Санкт-Петербург
Зарегистрирован: 2012-07-28
Сообщения: 107
Репутация: +  8  -
Профиль   Отправить e-mail  

dajaxice и 403 ошибка

UsCr:Уходит такой запрос:

Очевидно что не уходит "csrfmiddlewaretoken", смотрите https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax




Python, Django, Flask, Git, Emacs, Nginx, MySQL, SphinxSearch, Redis, Linux, FreeBSD
Мой блог, я на GitHub

Офлайн

#10 Авг. 13, 2012 14:20:08

Chern
От: Киев
Зарегистрирован: 2010-09-15
Сообщения: 71
Репутация: +  3  -
Профиль   Отправить e-mail  

dajaxice и 403 ошибка

UsCr, перепишите index с ипользованием RequestContext и посмотрите сюда



Офлайн

Board footer

Модераторировать

Powered by DjangoBB

Lo-Fi Version