djangowagtailwagtail-admin

How to make raw text file (to edit robots.txt) editor in Django Wagtail admin


The goal is to create a text file editor within the Wagtail admin site. Specifically for robots.txt file. I want the admin to update the file from the admin.

How can I do that?


Solution

  • There are some considerations to make for the robots.txt file hitting your server and doing a database read each time. You probably will want to consider some kind of caching layer here, however I have answered assuming you will resolve that and just want to get a Wagtail 'editor' solution here.

    Wagtail provides a contrib.settings module that allows you to have a settings model per site. This is a very helpful module that allows users, usually admin only users, to modify content that is specific to a site but does not suit the idea of a 'page'.

    https://docs.wagtail.org/en/stable/reference/contrib/settings.html

    Settings model

    from django.db import models
    
    from wagtail.admin.panels import FieldPanel
    from wagtail.contrib.settings.models import BaseSetting, register_setting
    
    @register_setting
    class MySettings(BaseSetting):
        robots = models.TextField(blank=True)
    
        panels = [
            FieldPanel('robots'),
        ]
    

    robots.txt view & template

    # using in your view
    def robots_view(request):
        robots = MySettings.for_request(request).robots
        ## return the content in your view
    
    User-agent: *
    {{ settings.app_label.MySettings.robots }}
    

    Considerations