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>
...дальше ничего интересного...