Code Monkey home page Code Monkey logo

django-ajax's Introduction

django-ajax

Fast and easy AJAX libraries for django applications.

Master Build Status PYPI Package PYPI Status PYPI License

Requirements

3.x

2.x

Installation

Install django-ajax in your python environment

1- Download and install package:

$ pip install djangoajax

Through Github:

pip install -e git://github.com/yceruto/django-ajax#egg=djangoajax

or simply with:

$ python setup.py install

2- Add 'django_ajax' into the INSTALLED_APPS list.

3- Read usage section and enjoy this feature!

Usage

@ajax Decorator

from django_ajax.decorators import ajax

@ajax
def my_view(request):
    do_something()

When the view does not return anything, you will receive this response (JSON format):

{"status": 200, "statusText": "OK", "content ": null}

Sending content

@ajax
def my_view(request):
    c = 2 + 3
    return {'result': c}

The whole result is converted into a JSON format as part of the content element:

{"status": 200, "statusText": "OK", "content": {"result": 5}}

Combining with others decorators

from django.contrib.auth.decorators import login_required
from django_ajax.decorators import ajax

@ajax
@login_required
def my_view(request):
    # if the request.user is anonymous then this view not proceed
    return {'user_id': request.user.id}

The location or path of the redirection response will be given in the content item, also the status and statusText will reflect what is going on:

{"status": 302, "statusText": "FOUND", "content": "/login"}

Template response

from django.shortcuts import render
from django_ajax.decorators import ajax

@ajax
def my_view(request):
    return render(request, 'home.html')

The JSON response:

{"status": 200, "statusText": "OK", "content": "<html>...</html>"}

Catch exceptions

@ajax
def my_view(request):
    a = 23 / 0  # this line throws an exception
    return a

The JSON response:

{"status": 500, "statusText": "INTERNAL SERVER ERROR", "content": "integer division or modulo by zero"}

AJAXMiddleware

If you are using AJAX at all times in your project, we suggest you activate the AJAXMiddleware described below.

Add django_ajax.middleware.AJAXMiddleware to the MIDDLEWARE_CLASSES list in settings.py and all your responses will be converted to JSON whereas the request was made via AJAX, otherwise it will return a normal HttpResponse.

Caution!

If this middleware is activated you cannot use the @ajax decorator. That will cause double JSON conversion.

AJAXMixin for class-based views

AJAXMixin is an object that call to AJAX decorator.

from django.views.generic import TemplateView
from django_ajax.mixin import AJAXMixin

class SimpleView(AJAXMixin, TemplateView):
    template_name = 'home.html'

The JSON response:

{"status": 200, "statusText": "OK", "content": "<html>...</html>"}

Enjoy And Share!

django-ajax's People

Contributors

akashkore5 avatar b3ni avatar duduklein avatar furious-luke avatar kavdev avatar luisza avatar yasminvc avatar yceruto avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

django-ajax's Issues

Customize ajax error message when DEBUG = False

Hi,

When an error occurs in production, we get, by default, an alert with the message "An error occurred while processing an AJAX request."

I know we can override the onError javascript function to display a custom message, but it would be helpful to be able to customize the default message. The current message is very "developer" oriented message, but not very user friendly (many users don't even know what an AJAX request is).

Besides, my sites are in French and Italian and I would like them to have by default a message in their own language.

I see 2 ways to achieve the above:

  1. add a ugettext_lazy to the shortcuts.py file where the message is hard-coded. This way, we can always translate the sentence above to something completely different (more user friendly) even in English.
  2. add a variable in the settings and use it instead of the hard-coded message. The hard-coded message would be used in the case the variable is not set in the settings file. The user would put the ugettext/ugettext_lazy is his settings directly or not according to his own needs. In this cause, we could create a dictionnary DJANGO_AJAX and add all the settings related to this app into it (like django-rest-framework does). This avoids having multiple variables across the settings.

I prefer the option 2, but am obviously open to discussion.

I'm willing to implement it and make a pull request if you agree.
What do you think?
Thanks

MiddleWare Error

Hello,
I get this error when I load the middleware with django 1.11:

 mw_instance = middleware(handler)
TypeError: object() takes no parameters

I added this to correct the message

class AJAXMiddleware(object):
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        response = self.get_response(request)
        return response


multiple ajaxGet arguments in .keyup don't work.

$("#search").keyup(function() {
    delay(function() {
        var data = {
            query: $("#search").val()
        }
        if (GLOBAL_VARS.link_id) {
            data.pk = GLOBAL_VARS.link_id;
        }
        ajaxGet(GLOBAL_VARS.distributorsSearchDistUrl, data, function(content) {
            $('#distributors').html(content);
            set_favorite();
        });
    }, 500);
});

don't want to work. First query works normal, with V I got:
http://127.0.0.1:8000/distributors/search_dist?query=V&pk=64
second query with VV returned me:
http://127.0.0.1:8000/distributors/search_dist?query=V without pk.
The same function but with $.get() works perfect, so I believe the problem is on your side.

Django views.generic not working

Using CreateView with AJAXMixin not rendering form properly.
Frontend ajax is done by jquery with .preventDefault()
"GET /create HTTP/1.1" 400 0

Django < 1.5 is not supported

Contrary to the documentation, the imports from the module django.http.response in shortcuts.py & encoder.py makes this app incompatible with versions of Django < 1.5.

Not receveing ADMIN error emails

I can't debug my deployed application because django-ajax is catching all errors and I'm not getting the ADMIN emails :/
(I'm now thinking of sending the error back from client side just to report it @_@)

Maybe there's a way to force admin error emails?

.js files not on the master branch.

Hi,

After spending a few hours searching for the static django_ajax/*.js files on the net, I finally found them on the stale gh-pages branch. I suspect they were missed in a site move or restructure.

400 error on @ajax decorator

Starting out with this library, and it gives me a 400 error with no information.

I'm using the exact code from the Usage section of the docs, applied to a brand new Django 1.7.2 project/app.
The dev server returns a 400 error, and the view code is never executed:

@ajax
def home(request):
    print "Running"
    pass

"Running" is not displayed on the console:

Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
[13/Jan/2015 16:26:33] "GET / HTTP/1.1" 400 0

Naming issue with PIP

Just discovered, pip freeze gives me "django-ajax==2.2.12", but attempt to install django-ajax==2.2.12 causes an error, because it registered like "djangoajax"

@ajax decorator returns blank page

I tried the example

from django_ajax.decorators import ajax

@ajax
def test_ajax(request):
    return render(request, 'base.html')

and I get nothing but a blank screen. What else am I supposed to do to make it work?

Install failes.

Maybe some unprintable character/encoding?
Maybe the readme file encoding?
PyCharm is very picky with that.

Collecting djangoajax
  Using cached djangoajax-2.3.0.tar.gz
    Complete output from command python setup.py egg_info:
    Traceback (most recent call last):
      File "<string>", line 20, in <module>
      File "/private/var/folders/zh/ntn59b4954l6tldmt4hn8bgc0000gn/T/pycharm-packaging2.tmp/djangoajax/setup.py", line 17, in <module>
        README = open(os.path.join(os.path.dirname(__file__), 'README.rst')).read()
      File "/Users/luckydonald/Documents/Programmieren/Python/my-project.git/virtualenv_3.4.3_brew.venv/bin/../lib/python3.4/encodings/ascii.py", line 26, in decode
        return codecs.ascii_decode(input, self.errors)[0]
    UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 4394: ordinal not in range(128)

    ----------------------------------------

Command "python setup.py egg_info" failed with error code 1 in /private/var/folders/zh/ntn59b4954l6tldmt4hn8bgc0000gn/T/pycharm-packaging2.tmp/djangoajax

Mac OS X 10.9.5, PyCharm 4.5, Python 3.4.3 (via brew) inside a virtualenv.

bildschirmfoto 2015-09-27 um 01 11 05

Elements added after page load

Hello. Does the plugin work for elements with data-ajax=true added dynamically after page load?. I can't get it to work in this case. Thanks

No matching distribution found

i'm try install on django 1.9.8 and python 2.7 but get the next error:

Collecting djangoajax
  Downloading https://files.pythonhosted.org/packages/25/f9/f3b70400ae9804f84c12c5f84cd9f8929e1f8f1769b773bf3d3425976b24/djangoajax-3.0.3.tar.gz
Collecting django>=2.0 (from djangoajax)
  Could not find a version that satisfies the requirement django>=2.0 (from djangoajax) (from versions: 1.1.3, 1.1.4, 1.2, 1.2.1, 1.2.2, 1.2.3, 1.2.4, 1.2.5, 1.2.6, 1.2.7, 1.3, 1.3.1, 1.3.2, 1.3.3, 1.3.4, 1.3.5, 1.3.6, 1.3.7, 1.4, 1.4.1, 1.4.2, 1.4.3, 1.4.4, 1.4.5, 1.4.6, 1.4.7, 1.4.8, 1.4.9, 1.4.10, 1.4.11, 1.4.12, 1.4.13, 1.4.14, 1.4.15, 1.4.16, 1.4.17, 1.4.18, 1.4.19, 1.4.20, 1.4.21, 1.4.22, 1.5, 1.5.1, 1.5.2, 1.5.3, 1.5.4, 1.5.5, 1.5.6, 1.5.7, 1.5.8, 1.5.9, 1.5.10, 1.5.11, 1.5.12, 1.6, 1.6.1, 1.6.2, 1.6.3, 1.6.4, 1.6.5, 1.6.6, 1.6.7, 1.6.8, 1.6.9, 1.6.10, 1.6.11, 1.7, 1.7.1, 1.7.2, 1.7.3, 1.7.4, 1.7.5, 1.7.6, 1.7.7, 1.7.8, 1.7.9, 1.7.10, 1.7.11, 1.8a1, 1.8b1, 1.8b2, 1.8rc1, 1.8, 1.8.1, 1.8.2, 1.8.3, 1.8.4, 1.8.5, 1.8.6, 1.8.7, 1.8.8, 1.8.9, 1.8.10, 1.8.11, 1.8.12, 1.8.13, 1.8.14, 1.8.15, 1.8.16, 1.8.17, 1.8.18, 1.8.19, 1.9a1, 1.9b1, 1.9rc1, 1.9rc2, 1.9, 1.9.1, 1.9.2, 1.9.3, 1.9.4, 1.9.5, 1.9.6, 1.9.7, 1.9.8, 1.9.9, 1.9.10, 1.9.11, 1.9.12, 1.9.13, 1.10a1, 1.10b1, 1.10rc1, 1.10, 1.10.1, 1.10.2, 1.10.3, 1.10.4, 1.10.5, 1.10.6, 1.10.7, 1.10.8, 1.11a1, 1.11b1, 1.11rc1, 1.11, 1.11.1, 1.11.2, 1.11.3, 1.11.4, 1.11.5, 1.11.6, 1.11.7, 1.11.8, 1.11.9, 1.11.10, 1.11.11, 1.11.12, 1.11.13, 1.11.14, 1.11.15, 1.11.16, 1.11.17)
No matching distribution found for django>=2.0 (from djangoajax)

i don't understand why getting this error please maybe someone idea.. thanks

Getting code 400 in browser

Good day Sir. Love the idea of this package.
I have been trying to get this to work on my project, but in my browser I keep getting 400 Bad request with a blank page. I even followed the example in the readme, still not working.

My specs:
Django 3.0.6
Python 3.7

I am suspecting this doesn't work with Django 3.

Your response will be appreciated.

Input (Form) Validation

I don't understand how django-ajax would work with Django Forms to provide input validation. Seems like processing raw JSON input in your views would be a major security hole. Do you have a recommendation for how to validate requests?

TypeError: __init__() got an unexpected keyword argument 'request'

Hi!

Example:

from django.http import Http404
from django_ajax.decorators import ajax

@ajax
def some_page(request):
    raise Http404

Traceback:

Traceback (most recent call last):
  File "/usr/local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner
    response = get_response(request)
  File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py", line 124, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/usr/local/lib/python3.6/site-packages/django/views/decorators/http.py", line 40, in inner
    return func(request, *args, **kwargs)
  File "/usr/local/lib/python3.6/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view
    return view_func(request, *args, **kwargs)
  File "/usr/local/lib/python3.6/site-packages/django_ajax/decorators.py", line 70, in inner
    return render_to_json(exception, **{'request': request})
  File "/usr/local/lib/python3.6/site-packages/django_ajax/shortcuts.py", line 109, in render_to_json
    return JSONResponse(data,  *args, **kwargs)
  File "/usr/local/lib/python3.6/site-packages/django_ajax/response.py", line 29, in __init__
    content=serialize_to_json(data, *args, **kwargs),
  File "/usr/local/lib/python3.6/site-packages/django_ajax/encoder.py", line 68, in serialize_to_json
    return json.dumps(data, *args, **kwargs)
  File "/usr/local/lib/python3.6/json/__init__.py", line 238, in dumps
    **kw).encode(obj)
TypeError: __init__() got an unexpected keyword argument 'request'

djangoajax==3.0.3

REASON_PHRASES error

remove from shortcuts.py

from django.http.response import REASON_PHRASES 

and add add this in shortcuts.py As reason phrases are supported from django 1.6

REASON_PHRASES = {
    100: 'CONTINUE',
    101: 'SWITCHING PROTOCOLS',
    102: 'PROCESSING',
    200: 'OK',
    201: 'CREATED',
    202: 'ACCEPTED',
    203: 'NON-AUTHORITATIVE INFORMATION',
    204: 'NO CONTENT',
    205: 'RESET CONTENT',
    206: 'PARTIAL CONTENT',
    207: 'MULTI-STATUS',
    208: 'ALREADY REPORTED',
    226: 'IM USED',
    300: 'MULTIPLE CHOICES',
    301: 'MOVED PERMANENTLY',
    302: 'FOUND',
    303: 'SEE OTHER',
    304: 'NOT MODIFIED',
    305: 'USE PROXY',
    306: 'RESERVED',
    307: 'TEMPORARY REDIRECT',
    400: 'BAD REQUEST',
    401: 'UNAUTHORIZED',
    402: 'PAYMENT REQUIRED',
    403: 'FORBIDDEN',
    404: 'NOT FOUND',
    405: 'METHOD NOT ALLOWED',
    406: 'NOT ACCEPTABLE',
    407: 'PROXY AUTHENTICATION REQUIRED',
    408: 'REQUEST TIMEOUT',
    409: 'CONFLICT',
    410: 'GONE',
    411: 'LENGTH REQUIRED',
    412: 'PRECONDITION FAILED',
    413: 'REQUEST ENTITY TOO LARGE',
    414: 'REQUEST-URI TOO LONG',
    415: 'UNSUPPORTED MEDIA TYPE',
    416: 'REQUESTED RANGE NOT SATISFIABLE',
    417: 'EXPECTATION FAILED',
    418: "I'M A TEAPOT",
    422: 'UNPROCESSABLE ENTITY',
    423: 'LOCKED',
    424: 'FAILED DEPENDENCY',
    426: 'UPGRADE REQUIRED',
    428: 'PRECONDITION REQUIRED',
    429: 'TOO MANY REQUESTS',
    431: 'REQUEST HEADER FIELDS TOO LARGE',
    500: 'INTERNAL SERVER ERROR',
    501: 'NOT IMPLEMENTED',
    502: 'BAD GATEWAY',
    503: 'SERVICE UNAVAILABLE',
    504: 'GATEWAY TIMEOUT',
    505: 'HTTP VERSION NOT SUPPORTED',
    506: 'VARIANT ALSO NEGOTIATES',
    507: 'INSUFFICIENT STORAGE',
    508: 'LOOP DETECTED',
    510: 'NOT EXTENDED',
    511: 'NETWORK AUTHENTICATION REQUIRED',
}

Import Error when trying to use AJAXMiddleware

ImportError: Module "django_ajax.middleware" does not define a "AJAXMiddleware," attribute/class

I wanted to move from using the ajax decorator to the Middleware. I have django_ajax included in installed apps and its middleware is also included.

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.humanize',
    'ndts.main',
    'ndts.members',
    'django_ajax',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'django_ajax.middleware.AJAXMiddleware,'
]

Add support for datetime.date type

Whenever there is a datetime.date type object in the response, it raises the following exeption:

TypeError: datetime.date(2016, 06, 22) is not JSON serializable

Problem with Http404

Hi! Thanks for lib.

Example:
views.py

from django.http import Http404
from django_ajax.decorators import ajax

@ajax
def some_page(request):
    raise Http404

After curl -H "X-Requested-With: XMLHttpRequest" http://127.0.0.1:8001/some_page/

Traceback

Internal Server Error: /some_page/
Traceback (most recent call last):
  File "/home/marsel/.virtualenvs/smi/lib/python3.5/site-packages/django_ajax/decorators.py", line 68, in inner
    return render_to_json(func(request, *args, **kwargs), **ajax_kwargs)
  File "/home/marsel/programming/ajax/http404/views.py", line 9, in some_page
    raise Http404
django.http.response.Http404

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/marsel/.virtualenvs/smi/lib/python3.5/site-packages/django/core/handlers/base.py", line 149, in get_response
    response = self.process_exception_by_middleware(e, request)
  File "/home/marsel/.virtualenvs/smi/lib/python3.5/site-packages/django/core/handlers/base.py", line 147, in get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/home/marsel/.virtualenvs/smi/lib/python3.5/site-packages/django_ajax/decorators.py", line 70, in inner
    return render_to_json(exception, request=request)
  File "/home/marsel/.virtualenvs/smi/lib/python3.5/site-packages/django_ajax/shortcuts.py", line 110, in render_to_json
    return JSONResponse(data,  *args, **kwargs)
  File "/home/marsel/.virtualenvs/smi/lib/python3.5/site-packages/django_ajax/response.py", line 29, in __init__
    content=serialize_to_json(data, *args, **kwargs),
  File "/home/marsel/.virtualenvs/smi/lib/python3.5/site-packages/django_ajax/encoder.py", line 65, in serialize_to_json
    return json.dumps(data, *args, **kwargs)
  File "/nix/store/qblj6pk8067czq8ya6bfllfvy0mndqjh-python3-3.5.2/lib/python3.5/json/__init__.py", line 237, in dumps
    **kw).encode(obj)
TypeError: __init__() got an unexpected keyword argument 'request'
[22/Sep/2016 09:36:09] "GET /some_page/ HTTP/1.1" 500 21133

raise Exception is just fine, because pop of request happens here.

@ajax decorator does not set http error code in JSONResponse

When raising an exception in a function decorated with @Ajax, the http status code is not set according to the error code:

HTTP status is 200 (OK):
image

However, the JSON-content is set correctly:
image

This can be fixed by changing response.py as follows (added status=data['status']):

class JSONResponse(HttpResponse):
    """
    Return a JSON serialized HTTP response
    """

    def __init__(self, data, *args, **kwargs):
        """
        This returns a object that we send as json content using
        utils.serialize_to_json, that is a wrapper to json.dumps
        method using a custom class to handle models and querysets. Put your
        options to serialize_to_json in kwargs, other options are used by
        response.
        """
        if not 'sort_keys' in kwargs:
            kwargs['sort_keys'] = settings.DEBUG

        super(JSONResponse, self).__init__(
            status=data['status'],
            content=serialize_to_json(data, *args, **kwargs),
            content_type='application/json'
        )

Result:
image

ajax request doesn't pick up csrf cookie value from previous ajax requests

We just stumbled over a problem when using ajax modals on our site for new site visitors. The modal request returns a new csrf cookie, but the csrftoken var in the jquery.ajax.idb.min.js on line 23 is only read once.

We fixed the issue by inlining the getCookie('csrftoken'); into the beforeSend function on line 53 :)

cannot import name 'ajax' from 'django_ajax.decorators'

I started getting this on my production site today. Development site still worked. I uninstalled and reinstalled the dev package keeping the exact same version and then I got the same error in dev environment as well. Then I bumped the version to latest and now no error.
Did you perhaps break your previous version when creating your new version?

setup.py name doesn't match pypi name

I'm using zc.buildout and since egg name specified in setup.py doesn't much name specified in pypi, I get this error:

Getting distribution for 'djangoajax'.
Installing djangoajax 2.2.12
Caused installation of a distribution:
django-ajax 2.2.12
with a different project name.
Got None.

Egg name in setup.py must match pypi name.

As a workaround in my setup.py I did this:

setup(
    install_requires=[
        'django-ajax',
    ],
    dependency_links = [
        'git+https://github.com/yceruto/[email protected]#egg=django-ajax-2.2.12',
    ],
)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.