“Best” way to integrate Django with an Ajax library

前端 未结 5 2017
后悔当初
后悔当初 2021-02-03 13:25

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 becaus

5条回答
  •  名媛妹妹
    2021-02-03 14:18

    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.

提交回复
热议问题