Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - Admin - Mandatory fields with ' * '

At present, Django admin will show all the mandatory fields with a bold labels. Is it possible mark with * in the label instead of bold labels?

like image 340
Sivasubramaniam Arunachalam Avatar asked Dec 08 '22 00:12

Sivasubramaniam Arunachalam


1 Answers

The Django admin uses templates to render the add/edit page for a model. It is possible to replace that template with one of your own (which extends from the original template) overriding the template blocks you need to in order to make the changes you want to.

Check out the Django docs regarding overriding admin templates for more information.

It's the admin/change_form.html template which you would need to alter in some way (since this template renders the page shown when you add a new instance or edit an existing one). The existing templates already apply a required class to the appropriate labels, so I would create a new template which looks like this:

{% extends "admin/change_form.html" %}

{% block extrastyle %}
    {{ block.super }}
    <style type="text/css">
        /* add an asterisk using CSS */
        .required:after {
            content: " *";
        }
    </style>
{% endblock %}

Apply to a Single Model

You should use a model admin class if you want this template to be used for specific models, setting the change_form_template attribute, as described in this section of the docs to the location of the template file you have created.

Apply to a Single App

If you want template to apply to models in an entire app create a templates folder inside the root of the app. Django will automatically look for templates there, so if you create a folder called admin and place a file in there called change_form.html it will automatically override the default Django template of that name (admin/change_form.html).

Project Wide

In order to apply this template project wide create a folder somewhere (not inside an app) called templates. Again place your new template in this directory at admin/change_form.html.

Next edit the template directories Django setting specifying the location of this directory in order to allow Django to find the template and override the default templates in the same way as before only project wide and not just app wide.


This is quite a complex set of things to do, especially for such a simple change and you may find it tricky if you have not worked with admin templates before (or even if you have).

Hopefully you now understand what is required to change an admin template, its actually fairly elagant (as is Django) but in my opinion not worth the effort just to change to some asterisks.

like image 83
Marcus Whybrow Avatar answered Dec 09 '22 14:12

Marcus Whybrow