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

Question:

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']
Asked By: Jarad

||

Answers:

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

Answered By: whp

If we stick to the screen capture from op, here is what can be done:

class AdminExample(admin.ModelAdmin):
  readonly_fields = ('show_url',)
  fields = (......, "show_url",)

  def show_url(self, instance):
    url = reverse('help_link')
    response = format_html('<a href="{0}">{1}</a>', url, 'help_link')
    return response

Then don’t forget to add in urls.py and views.py for the link to work.

Here is the result:

enter image description here

Answered By: Pozinux