joestump / django-ajax Goto Github PK
View Code? Open in Web Editor NEWA simple framework for creating AJAX endpoints in Django.
Home Page: http://github.com/joestump/django-ajax
License: BSD 3-Clause "New" or "Revised" License
A simple framework for creating AJAX endpoints in Django.
Home Page: http://github.com/joestump/django-ajax
License: BSD 3-Clause "New" or "Revised" License
django-taggit needs to be specified in setup.py as a requirement:
Error: No module named taggit.utils
Would be great to have this as a pypi package.
I am relatively new to Django, I can't figure out how to do this without writing endpoints.py custom code. I'd like to be able to have an ajax call that operates on the Django User model (django.contrib.auth.models.User). Is there a way to create endpoints for an application where I don't have the ability to check in an 'endpoints.py' file?
I am able to write customer ad-hoc endpoints.py to get at the same data. I was just hoping I was overlooking a way to get at someone elses application models easily without subclassing them.
-g
Hi !
I'm trying to get starting with django-ajax. It looks perfect for what I'd like to do!
First problem is that I get 403 forbidden response when I try a post in my JS. Which makes sense if I didn't get the CRSF token... But I expected the app to take care of that. No?
Another point, I get something when I just try to browse to the ajax address from the browser. Shouldn't the app check for is_ajax() request and throw an error if not?
I'm just getting the feeling that I'm doing something wrong. Is it me or have you encountered those problem before?
Thanks for your time!
Vince
error response list below
{"traceback":[{"line":48,"code":"result = f(*args, **kwargs)","file":"E:\\ajax \\decorators.py","in":"json_response"},{"line":69,"code":"separators=(',', ':')))","file":"E:\\ajax\\views.py","in":"endpoint_loader"}, {"line":334,"code":"**kw).encode(obj)","file":"C:\\Program Files\\Python27\\lib\\site- packages\\simplejson\\__init__.py","in":"dumps"}],"data":{"message":"__init__() got an unexpected keyword argument 'namedtuple_as_object'","code":500},"success":false}
error code: 500
error message: "init() got an unexpected keyword argument 'namedtuple_as_object'"
how can i solve this problem?
is that errors relate in django or simplejson ?
i use django 1.5.1
thank you.
When I try to update a DateTimeField in an application with the setting USE_TZ = True
the ModelEndpoint
fails with the exception can't compare offset-naive and offset-aware datetimes
.
How can this be fixed? Or is it a must to override the functions in this situation?
Any help appriciated.
As far as I can tell (please correct me if I'm wrong), the library at present does not support setting a value for ManyToManyFields on models. Ideally, I would like to be able to pass an array of values to the create endpoint to create a new object, i.e.:
$.ajax("/ajax/myapp/mymodel.json",{
data: {'foo':[1,2]}, //jquery handles converting this into the correct format as below
type: 'POST'});
=> POST /ajax/myapp/mymodel.json?foo=1&foo=2
Class MyModel(models.Model):
foo = models.ManyToManyField(MyOtherModel)
Why not allow them to be imported directly? I have an endpoint that looks like this, and it seems to be a lot of rigamarole to have to subclass BaseEndpoint just so I can get access to the encoding function.
def browse_group(request):
group = get_object_or_404(Group,pk=request.POST['group_id'])
all_people = Person.objects.order_by('last_name').filter(groups=group)[:10]
return {'people':_encode_data(all_people)}
The README should include information on which methods should be called via GET and which should be called via POST. Relatedly, if ajax/{some_app_name}/{model}.json
and /ajax/{some_app_name}/{model}/{pk}/(update|delete).json
can be called via GET, they probably shouldn't be.
I have tried faithfully to follow directions getting django-ajax set up, but my attempts to use ModelEndpoints or the simple echo example just produce 403 errors. I had to update the urls.py file to remove defaults from the import command. No idea whether this means the problem goes deeper, and I may be doing something wrong, but I'd be curious if there is an incompatibility with the version 1.6.1.
When running through your example in your README, it returns AJAXError(404, 'Invalid user.'). When you actually return the AJAXError object, you get an _AJAXError() is not JSON serializable_ error.
Using this example code:
class MyEndpoint(BaseEndpoint):
def __call__(self, request):
try:
user = User.objects.get(pk=int(request.POST['user']))
except User.DoesNotExist:
return AJAXError(404, 'Invalid user.')
return self._encode_record(user)
my_endpoint = MyEndpoint()
In my java script I just tested with:
$.post('/ajax/trip_summary/my_endpoint.json', {
user: 8123912312,
});
Django-ajax works only with python 2.x, and breaks badly under python 3.
Is there a way to get encode_data to recognize models pulled in with select_related in the queryset passed to it?
I am looking at creating some predefined authentication types to assist with people trying to quickly move towards having a fully working API solution. Currently I am looking at implementing the following:
Once I have these setup, I am going to have to work out where to implement the authentication. Currently I am thinking either in the current authenticate
method or within the login_required decorator.
This will also require a few default settings that can be changed to implement the different auth endpoints.
Just wanted to put this here to start a discussion.
You fail to mention that you need to install the decorator (http://pypi.python.org/pypi/decorator) app otherwise you get "Error: No module named decorator". Although somewhat easy to track down, it would be handy to have it in the read me.
Is there a way to set up functions in other files, such as views.py, as Ajax endpoints? I
I think it needs to be made clear that the model names in urls for ModelEndpoints such as /ajax/my_app/mymodel/{pk}/tags/add.json
must not be capitalised or the endpoint_loader will fail.
eg if you posted to /ajax/my_app/Mymodel/{pk}/tags/add.json
then hasattr(my_app.endpoints, 'Mymodel')
will return true because endpoints
imports Mymodel
to create the ModelEndpoint
, but this will make the endpoint_loader
think it's an ad-hoc endpoint instead.
From endpoint_loader
:
if hasattr(module, model):
# This is an ad-hoc endpoint
endpoint = getattr(module, model)
It will then fail when it tries to serialize the model object via data = endpoint(request)
ajax/views.py and ajax/utils.py import from django.utils.importlib, which will be going away in Django 1.9.
Since Django 1.8 is just on the verge of release, there's still plenty of time to work on a fix before 1.9 shows up.
If an AJAXError is raised, I get another error which belongs to the message encoding inside of AJAXError.
'exceptions.ImportError' object has no attribute 'decode'
You can fix it by removing decode()
in this line. Don't know if this would have any other implications, yet, though.
'message': smart_str(self.msg.decode())
Hi Joe,
sorry for dropping this here, didn't know where else.
I wired your package to django and created
'site/app/endpoints.py'
with following content:
def foo(request):
return {"foo":"bar"}
from javascript:
$.ajax(
{
url: '/ajax/claims/foo.json',
dataType: 'json',
type: 'GET',
complete: function(jqXHR, textStatus) {
alert("status: "+textStatus)
}
}
);
however, i receive a code 400 (BadRequest).
Does this indicate, that an url has to be set somewhere?
From the readme i didn't get if or how those should be set?
The endpoint_loader dynamically imports modules based on the URL:
try:
module = import_module('%s.endpoints' % application)
except ImportError, e:
raise AJAXError(404, _('AJAX endpoint does not exist.'))
The trouble with this is that programming errors (syntax errors and such like that would prevent the endpoints module from being imported) are disguised as client errors, making debugging unnecessarily complicated. Perhaps, when DEBUG is set, simply raise the ImportError.
I'm trying to test my Ajax methods by issuing requests from my browser as I write them, and notice using the decorator @csrf_except around my endpoint function doesn't work, because the function in endpoints.py isn't the real view function, so the decorator has no effect. Any idea how to get around this?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.