Add an AdSense Ads.txt File to Django

Posted: September 08, 2024 | Updated: September 08, 2024

If you are using Google AdSense ads on your Django site, you will need to add an ads.txt file to your site. Adding an ads.txt file in Django can be a bit tricky, but here's how to do it.

Create the ads.txt file on your computer. Then upload the file to your Django static folder.

Then, add the following code to your Django app's views.py file.

from django.http import HttpResponse
from django.conf import settings
import os

def serve_ads_txt(request):
    # Make sure STATICFILES_DIRS is set if STATIC_ROOT is not set
    if settings.STATIC_ROOT:
        file_path = os.path.join(settings.STATIC_ROOT, 'ads.txt')
    else:
        # Handle the case where STATIC_ROOT is not defined
        file_path = os.path.join(settings.BASE_DIR, 'static', 'ads.txt')

    if os.path.exists(file_path):
        with open(file_path, 'r') as file:
            content = file.read()
        return HttpResponse(content, content_type='text/plain')
    else:
        return HttpResponse('File not found', status=404)

Then add the following code to your urls.py file.

from .views import serve_ads_txt

urlpatterns = [
    path('ads.txt', serve_ads_txt),
]

After that, check the file on your site. 

For example, the URL should be: https://www.sitename.com/ads.txt

© 2024 Webapptiv. All rights reserved.