Django apps using class-based views and ajax?

后端 未结 3 1341
逝去的感伤
逝去的感伤 2021-01-31 04:50

I\'m learning Django and I found class-based views and I wonder how to implement Ajax on those views.

I searched github for a django project and I found some using class

3条回答
  •  闹比i
    闹比i (楼主)
    2021-01-31 05:47

    without using the popular dajaxic and dajax packages, its still a straightforward affair.

    It would help to write a decorator that just wraps around django's is_ajax() function for request objects like so:

    def ajax_request(function):
        def wrapper(request, *args, **kwargs):
            if not request.is_ajax():
                return render_to_response('error/ajax_required.html', {},
                    context_instance=RequestContext(request))
            else:
                return function(request, *args, **kwargs)
        return wrapper
    

    assuming there is a template called ajax_required to handle this particular failure. Something like this prevents a user from entering your ajax specific url in the browser if thats what you don't want.

    Because it makes for a shorter example, the following is a class based ajax view that renders a template.

    from django.views.generic.base import TemplateView
    
    class AjaxGeneral(TemplateView):
        template_name= None
        def get(self, request):
            data={}
            return render_to_response(self.template_name, data,
                context_instance=RequestContext(request))
    
        @method_decorator(ajax_request)
        def dispatch(self, *args, **kwargs):
            return super(AjaxGeneral, self).dispatch(*args, **kwargs)
    

    now for everything ajax that just needs to render an html snippet you can define short class based views like:

    class ShowSomeTable(AjaxGeneral):
        template_name="some_table.html"
    

    Assuming some_table.html has some html snippet in it.

    Now your urls.py entry for this view will look like:

    url(r'showtable/$', ShowSomeTable.as_view()),
    

    and you can call it in the js as normal like:

    $(#dynamic-content).load('/showtable');
    

提交回复
热议问题