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.
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.
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("")
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
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