pythad
pythad

Reputation: 4267

Do I need to use request.is_ajax() in my views?

I am learning to use Ajax with Django, many tutorials simply check if request.method == 'GET' or POST. I am curious for what do we need .is_ajax() then. Is it normal no to use it or tutorials just show basic concepts?

Upvotes: 2

Views: 1255

Answers (1)

Giuseppe Pes
Giuseppe Pes

Reputation: 7912

I am curious for what do we need .is_ajax() then. Is it normal no to use it or tutorials just show basic concepts?

Yes, it is totally normal not to use is_ajax. Most of the time what you care about in your views is the HTTP verb (e.g. GET, POST, PATCH..). However there are certain cases where you want to know if the request is an AJAX request. Why? because you might want to return a different result depending if the request is ajax or not.

The most common use for this solution is PJAX. When you use a pjax technology, if the request is not an ajax request you render the entire page, whereas if the request comes from ajax you render only a partial of the page. Then the partial page is added in the correct place in the webpage by some sort of lib, such as https://github.com/defunkt/jquery-pjax.

For example, this is a mixing I wrote to use Pjax in django:

import os

from django.views.generic.base import TemplateResponseMixin

class PJAXResponseMixin(TemplateResponseMixin):
    pjax_template_name = None
    pjax_suffix = "pjax"
    pjax_url = True

    def get_context_data(self, **kwargs):
        context = super(TemplateResponseMixin, self).get_context_data(**kwargs)
        context['inner_template'] = self.pjax_template_name
        return context

    def get_template_names(self):
        names = super(PJAXResponseMixin, self).get_template_names()
        if self.request.is_ajax():
            if self.pjax_template_name:
                names = [self.pjax_template_name]
            else:
                names = self._pjaxify_template_var(names)
        return names

    def get(self, request, *args, **kwargs):
        response = super(PJAXResponseMixin, self).get(request, *args, **kwargs)
        if sel

f.pjax_url :
 response['X-PJAX-URL'] = self.request.path
return response

def _pjaxify_template_var(self, template_var):
    if isinstance(template_var, (list, tuple)):
        template_var = type(template_var)(self._pjaxify_template_name(name) for name in template_var)
    elif isinstance(template_var, basestring):
        template_var = self._pjaxify_template_name(template_var)
    return template_var

def _pjaxify_template_name(self, name):
    container = self.request.META.get('HTTP_X_PJAX_CONTAINER', False)
    if container is not False:
        name = _add_suffix(name, clean_container_name(container))
    return _add_suffix(name, self.pjax_suffix)


#################################################
#               HELPER METHODS                  #
#################################################


def clean_container_name(name):
    return name.replace('#', '')


def _add_suffix(name, suffix):
    if "." in name:
        file_name, file_extension = os.path.splitext(name)
        name = "{0}-{1}{2}".format(file_name, suffix, file_extension)
    else:
        name += "-{0}".fomat(suffix)
    return name

Basically, this mixing renders the default template if the request is not an ajax request. Whereas if the request is AJAX, it renders the pjax_template, if there is one, or the name of the default template prefixed with pjax.

Upvotes: 5

Related Questions