2

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.

Christian Brink
  • 663
  • 4
  • 18
  • Adding `noindex` fora a redirect response makes little sense. Search engines don't index redirects. Having `noindex` on a redirect is redundant. – Stephen Ostermiller Mar 11 '22 at 10:07

3 Answers3

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("")
kloddant
  • 1,026
  • 12
  • 19
1

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
0

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
ErezO
  • 364
  • 2
  • 10