Django Admin: adding runtime text next to a field

I want to add text next to the django admin interface field.

A warning must be created at runtime inside the python method. I know python and django ORM well, but I don’t know how to get the text next to the field.

The text should be a warning. Raising ValidationError in clean () is not a solution since the user can no longer edit the page. It should just be a warning message.

+3
source share
3 answers

You can use your own subclass ModelFormfor the administrator by adding an attribute help_textfor the corresponding field when you initialize it and configure it accordingly.

# forms.py

class YourModelForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(YourModelForm, self).__init__(*args, **kwargs)
        self.fields['field_in_question'].help_text = generate_warning()

# admin.py

class YourModelAdmin(admin.ModelAdmin):
    form = forms.YourModelForm

    # And here you can specify custom CSS / JS which would make
    # `help_text` for that particular field look like a warning.
    # Or you can make it generic--say, style (and maybe reposition w/js) all tags
    # like <span class="warning"> that occur within the help text of any field.

    class Media:
        css = {"all": ("admin_warning.css", )}
        js = ("admin_warning.js", )
+5

, . Django. , , , change_form.html. original.

, .

: contrib/admin/templates/admin/change_form.html, include includes/fieldset.html, . - , , named, , . change_form.html .

0

, , , list_display admin.

class MyModel(models.Model):
    myfield = models.CharField(max_length=100)

    def myfield_with_warning(self):
       return '%s - %s' % (self.myfield, '<span class="warn">My warning message</p>'
    myfield_with_warning.short_description = 'My field verbose name'
    myfield_with_warning.allow_tags = True

class MyModelAdmin(models.ModelAdmin):
    list_display = ('myfield_with_warning',)

If this is not what you need, write more precisely where you want to display a warning message.

0
source

All Articles