'Django: At the view level, can I add a 'noindex' header to a 'redirect' response?

I can use robots.txt, and I can use custom Django middleware, but I'd like to know whether this is something that can be done at the view level.



Solution 1:[1]

Since you are probably going to be doing this quite often, you could make it into a decorator.

decorators.py

def robots(content="noindex, nofollow"):
    
    def _method_wrapper(func):
        
        @wraps(func)
        def wrap(request, *args, **kwargs):
            response = func(request, *args, **kwargs)
            response['X-Robots-Tag'] = content
            return response

        return wrap
        
    return _method_wrapper

views.py

from .decorators import robots

@robots("noindex")
def something(request):
    return HttpResponse("")

@robots("all")
def something_else(request):
    return HttpResponse("")

Solution 2:[2]

You can add a noindex tag using the following snippet:

from django.http import HttpResponse

response = HttpResponse("Text only, please.", content_type="text/plain")
response['X-Robots-Tag'] = 'noindex'
return response

Solution 3:[3]

If you are using Class Based Views, you can also create a mixin:

mixins.py

class NoIndexRobotsMixin:
    def dispatch(self, request, *args, **kwargs):
        response = super().dispatch(request, *args, **kwargs)
        response['X-Robots-Tag'] = 'noindex'
        return response

views.py

class MyView(NoIndexRobotsMixin, generic.View):
    pass

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 kloddant
Solution 2 ErezO
Solution 3 Christopher Grande