Search code examples
pythondjangodjango-formsdjango-admin

Django add hard-coded href links to an admin model's form view page


In Django's admin panel, how do I add hard-coded links to a Django model's form page (/add/ page). These are links to documentation that will never change. I want these links to appear every time on the form as a reference for the user to figure out what values to input into the fields.

Do I need: Custom field? Built-in field already? Modify the admin templates somehow? Add a helper function somewhere?

I'm not referring to the "change list" view; I am referring to the /change/ or /add/ page view when you go and add or edit an object within a model.

add links in Django admin model form

models.py

class DateRange(models.Model):

    date_name = models.CharField(max_length=100)
    adwords_name = models.CharField(max_length=100)
    bingads_name = models.CharField(max_length=100)

    def __str__(self):
        return self.date_name

forms.py

class DateRangeAdminForm(forms.ModelForm):
    class Meta:
        model = DateRange
        fields = '__all__'

admin.py

@admin.register(DateRange)
class DateRangeAdmin(admin.ModelAdmin):
    form = DateRangeAdminForm
    list_display = ['date_name', 'adwords_name', 'bingads_name']

Solution

  • Extending change_form.html could work -- it'll add links at the top.

    Create this file in your namespaced templates directory, referred to here as "templates-dir"

    templates-dir/admin/myapp/daterange/change_form.html:

    {% extends "admin/change_form.html" %}
    
    {% block object-tools %}
        {{ block.super }}
        <ul>
            <li>
                <a href="https://link1.com">Adwords documentation</a>
            </li>
            <li>
                <a href="https://link2.com">Bing ads documentation</a>
            </li>
        </ul>
    {% endblock object-tools %}
    

    Relevant docs:

    https://docs.djangoproject.com/en/2.0/ref/contrib/admin/#overriding-admin-templates

    https://docs.djangoproject.com/en/2.0/howto/overriding-templates/#overriding-from-an-app-s-template-directory