How to add ads.txt on Django as requested by Google?

Google strongly recommends using an ads.txt file on Your websites. If there’s an issue with ads.txt on your site, you’ll see an alert in your AdSense account. In general, it is easy to add the ads.txt file on static sites or WordPress blogs. All you have to do is upload the file to the server or use a plugin on WordPress sites.

in Django, things are a little more complicated. You have 2 options: use a dedicated package or create a custom view with the ads.txt content.

a) Use django-ads-txt, a simple Django app to manage ads.txt file from admin panel

django-ads-txt is a basic Django application to manage Authorized Digital Sellers (ads.txt) file based on iabtech lab specification.

Steps:
1. Install the package

pip install django-ads-txt

2. Add ‘ads_txt’ to your INSTALLED_APPS setting.

3. Run the migrate management command

4. To activate ads.txt generation on your Django site, add the next line to your URLconf:

url(r'^ads\.txt', include('ads_txt.urls')),

5. Add the domains you need to appear from the admin panel.

b) Create a custom view with the ads.txt content

Another way if you do not want to install a package is to create a custom view with the ads.txt content, following the steps below:

1. In the views.py file create the ads_txt function:

# for ads.txt
from django.http import HttpResponse
from django.views.decorators.http import require_GET


@require_GET  # only allow GET requests
def ads_txt(request):
    content = 'google.com, pub-xxx, DIRECT, xxx'
    return HttpResponse(content, content_type="text/plain")

2. Add the route in the urls.py file

from your_application.views import ads_txt

...
path('ads.txt', ads_txt),

If you have another method please share it in the comments.

Leave a Comment

How to? Ask a Question