开发者

"Best" way to integrate Django with an Ajax library

开发者 https://www.devze.com 2023-03-12 05:19 出处:网络
Obviously, horses for courses, but what are some good ways to integrate javascript libraries with one\'s Django application?

Obviously, horses for courses, but what are some good ways to integrate javascript libraries with one's Django application?

I'm planning on using jQuery, mostly because it seems popular and looks powerful (but I'm open to other suggestions).

Are there python-side libraries that are very helpful or essential? Or is it best simply to create JSON views, and hand-code the javascript (using an appropriate javascript framework)?

I've looked (briefly) at Dajax, but based on the scant documentation, it's not clear that it really gives me very much. I would certainly prefer something with a bit more documentation.

Other answers here suggest that pjax doesn't necessarily work well with many browsers, so that's out.

Edit: Thanks everyone. I'll be looking at tastypie to simplify exposing some json views, and man up to write some javascript by hand (Which having done a tiny bit earlier this y开发者_运维百科ear, seems much better than it was in the late 90s).


Remember, Just because it's ajax does not mean you need to return a json dump. You can indeed return a rendered template.

It's true, that the 'right way' is to construct all your tags in javascript, and fill in that data with the json data, but let's face it, that's such a pain in the rump... so much so that they're developing a jquery template language.

You also can't just dump a query set. You need to construct your json data by hand. All these tutorials and suggestions seem to gloss over that fact. From the django docs:

def convert_context_to_json(self, context):
        "Convert the context dictionary into a JSON object"
        # Note: This is *EXTREMELY* naive; in reality, you'll need
        # to do much more complex handling to ensure that arbitrary
        # objects -- such as Django model instances or querysets
        # -- can be serialized as JSON.
        return json.dumps(context)

What I've done is actually write a mixin for the new class based views that renders a choice of templates depending on wether it's an ajax page load or not. I then put the fragment of what I'd want returned in one fragment, and in another wrapper template, extend base.html and include the fragment template.

class AjaxTemplateMixin(TemplateResponseMixin):
    ajax_template_name = None

    def get_template_names(self):
        if self.ajax_template_name and self.request.is_ajax():
            self.template_name = self.ajax_template_name

        return super(AjaxTemplateMixin, self).get_template_names()    

This allows me to only write the template once, and then without having to manually construct dom elements in javascript. It's very little extra work, and especially if you're not writing an api, it's the way to go.


I would suggest that you simply create your own javascript and AJAX views. Ruby on Rails long had the opposite problem: forcing people to do AJAX in a certain way, and it was always a point of conflict for people. Recently, they finally realized their folly and decoupled AJAX from the framework so you can easily use whatever library you like.

This is a feature of Django. It may seem more difficult, but trust me, it ends up being infinitely better having control end-to-end.


On python side, I'd suggest to look at piston and tastypie.

(Starting with AJAX + Django myself, I also found Dajax, but went with piston—felt more ‘unix-way’ for me, don't like these all-in-one solutions. Though piston wasn't updated for a long time now, so I'd recommend tastypie, which is actively maintained.)

EDIT. There's also a similar project, django-rest-framework. Never used it myself yet, it's pretty new.

Basically, these libs help you create a fully working read-write API for your models, so you can perform create-read-update-delete operations from your javascript via HTTP. You don't need to define any views or serializers. Instead, you define resources, which is a decent abstraction, I think.

And it usually takes just a few lines of code, especially if your resources are tied to models.

However, if you need something more complicated, you can rethink your design write your views. With class-based views, it's pretty easy, too. Take a look at this snippet for example.


I've always just made my own views which serve up JSON, and written the JavaScript myself (normally using jQuery). Obviously, this all depends on what you're trying to do - if there's a specific need you've got which an existing app solves, then by all means use it.

Serving up JSON is pretty trivial (just dump out some JSON and return it as an HttpResponse), like this:

def get_user_ids(request):
    if not request.is_ajax():
        raise Http404

    return HttpResponse(simplejson.dumps({'ids': [u.pk for User.objects.all()]}))

Code above intended to be demonstrative, I'm not suggesting you make a view which shows all your user IDs.


Dajax is quite straight forward. You'd better tell us more about what puzzles you in Dajax.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号