Issue
I have a Django model where in I want to display help text as shown below:
class StaffRoles(models.Model):
role = models.CharField(primary_key=True, max_length=8, verbose_name="Role", help_text='Field accepts all uppercase only')
role_short_text = models.CharField(max_length=35, verbose_name='Short Desc')
role_long_text = models.CharField(max_length=250, verbose_name='Description')
Now when I use the model in Django generic CreateView
to add a new Role, the help text is displayed in the page in a default style just next to the input field role
.
What I am trying to do is to add some style to the help text being displayed, and to that end I tried to modify my template code as shown below:
The template code:
...
{% for field in form.visible_fields %}
{% if field.name == "role" %}
{{ field }}
<small style="color:teal">{{ field.help_text|safe }}</small>
{% endif %}
{% endif %}
However, to my dismay the help text is displayed twice - i.e. the resultant help text as a result of the new code line added, plus the text that was originally displayed.
Is there a way I may display the help text with some css styles added?
Solution
try this code:
from django.utils.safestring import mark_safe
from django.utils.translation import gettext_lazy as _
class StaffRoles(models.Model):
role = models.CharField(primary_key=True, max_length=8, verbose_name="Role",
help_text = mark_safe(_(
'<small style="color:teal">Field accepts all uppercase only</small>'
))
)
[..]
or you may override the default style of django admin contrib module.
Update
As second option you need to override change_form.html
to add you custom css file.
- under
templates
create folders like/admin/YOUR-APP/change_form.html
- add this code
{% extends "admin/change_form.html" %}
{% block extrastyle %}
<style>
/* your custom style */
</style>
{% endblock %}
have a look at base template for admin contrib package under venv\Lib\site-packages\django\contrib\admin\templates\admin
(i'm on windows using venv
)
and refer to https://docs.djangoproject.com/en/3.1/ref/contrib/admin/#overriding-admin-templates for more details ..
also you can completely override the look and feel of admin interface, there's already themes ready for use on pypi
.
Answered By - cizario
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.